Python is currently the most used programming language in the world, and the unique reason is that Python developers are happy building software with it.
Its easy syntax, an extensive amount of libraries, and fast learning curve have gained the hearth of both beginners and experienced developers.
So today I'll share 6 of the best Python tricks that are not usually taught. π
All the examples are on this Github repo, available after subscribing, so be sure to take a look at them.
--> Access and Download the source code of this article here
Β
π Giveaway β‘
We are giving away any course you need on Udemy. Any price any course.
To enter you have to do the following:
- π React to this post
- βοΈ Subscribe to our newsletter <-- Very important
Β
Select a random element from a sequence
The random
package from the standard library has a lot of useful functions. But random.choice(seq)
is a particularly useful one.
It allows you to pick a random element from an indexable sequence, for example, lists
, tuples
, or even strings
import random as r
my_list = [1, 2, 3, "go"]
print(r.choice(my_list))
# Random item
Practical example
A book picker function that receives a sequence of books gets a random choice, removes the item from the list, and returns the choice as a string
# We import only the function we need
from random import choice
def book_picker(books):
book_choice = choice(books)
books.remove(book_choice)
return f"You picked {book_choice}"
books = ["Harry potter", "Don Quixote", "Learn Python by Daniel Diaz", "Dracula"]
print(book_picker(books)) # Random choice
print(books) # Remaining books
Limitations and Exceptions
If you try to use random.choice(seq)
in a non-indexable sequence, for example, dictionaries
, sets
, and numeric types
, Python will raise an Error.
# With Dictionary
import random as r
scores = {"Jhon": 4, "Ben": 3, "Diana": 5}
print(r.choice(my_scores)) # Key error
Also if the sequence is empty Python will raise an IndexError
.
# With an empty sequence
import random as r
empty_list = []
print(r.choice(empty_list)) # Index error
Unpacking elements with *
Sometimes we need to print the elements of an iterable separated by a space, and the most common solution I've seen is
my_list = [1, 2, 3, 5, 7]
for i in my_list:
print(i, end=" ") # 1 2 3 5 7
Although this solves the problem, the code isn't that pythonic. There is a simpler solution using the unpacking operator "*"
my_list = [1, 2, 3, 5, 7]
print(*mylist) # 1 2 3 5 7
As you can see the unpack operator is always set at the left of an iterable, and it tells Python:
Assign each element from this iterable to the desired tuple or list
Remember that an iterable is any sequence we can iterate over with a for loop. If you want to check if a data type is iterable, use the iter()
function.
print(iter("This is a string")) # Str Iterable object
print(iter(["this", "is", "a", "list"])) # List iterable object
print(iter(1))
# Raises an error
# Integers can't be iterated
Using unpacking with variables
Probably after you know the power of the unpacking operator, you would like to use it to store data in variables. So let's see how to do it
string = "Let's learn Python"
# We want to assign the unpacked result in var1
var1 = [*string]
print(var1)
# ['L', 'e', 't', "'", 's', ' ', 'l', 'e', 'a', 'r', 'n', ' ', 'P', 'y', 't', 'h', 'o', 'n']
The [*iterable]
part may look confusing so let me explain it.
When we unpack an iterable python needs some data structure to store each element of that iterable, therefore we are creating a list ([]
) outside the *
operator.
If we try to get the type of a variable resulting from the *
operator we get
another_str = "The * operator"
# Using a list outside the unpacking
var2 = [*another_str]
print(type(var2)) # List
# Using a tuple
# Tuples ends with a comma
var3 = (*another_str,)
print(type(var3)) # Tuple
Of course, if you try to unpack without a list or tuple outside, you'll get a SyntaxError
bad_variable = *"Bad String"
# Syntax error
Unpacking has much more uses, and I could do an exclusive article about it. π
Using set
to optimize operations
According to the python documentation, the set(iterable)
class creates a set object from an iterable.
As some of you may know a set is an unordered data structure, (therefore non-indexable) and one of its characteristics is that doesn't allow duplicated items.
Practical example
Function that removes duplicates, and returns a sorted list.
def eliminate_duplicates(lst):
"""
Returns a sorted list, without duplicates
"""
new_list = list(set(lst))
new_list.sort()
return new_list
list1 = [25, 12, 11, 4, 12, 12, 25]
print(eliminate_duplicates(list1))
View attrs and methods of a class without exiting the editor
The dir()
function returns the attributes and methods of a class. We can use this useful trick to list all the definitions inside a class type.
-> $ python
string = "A string"
print(dir(string))
# ['__add__', .....,'upper', 'zfill']
For example, if we were looking for a string method that will convert our string into uppercase, and we are just too lazy to open the browser, we just run the dir
function with a string as an argument and search for the right method
Practical example
The best approach we can get from dir
is when using 3rd party packages, we can get all the info we need from a class without exiting the terminal
-> $ python
from django.views import View
print(dir(View))
# ['__class__', '__delattr__', .... 'setup']
Slices Operations
A slice is nothing but a way of accessing certain parts of a sequence. In python, slices allow us to do multiple tricks.
Reversing sequences
# Reversing lists
lst = ["Fun", "is", "Programming"]
lst = lst[::-1]
print(lst) # ['Programming', 'is', 'Fun']
# Reversing strings
string = "Dog running on the park"
string = string[::-1]
print(string) # krap eht no gninnur goD
Practical example
Function that returns a sequence until the given index
def cutoff(seq, index):
if not len(seq) > index:
return "Sorry the index is bigger than the sequence"
return seq[:index]
long_string = "This is a long description of a blog post about Python and technology"
print(cutoff(long_string, 15))
# This is a long
print(cutoff(long_string, 70))
# Sorry the index is bigger than the sequence
Call a debugger in 10 letters
The function breakpoint
is available from python 3.6+. This will call a session of pdb.set_trace()
.
It may sound like a pure convenience (And maybe it does) but for me is a really short and elegant way of calling a debugger
Example
n_odds = 0
for i in range(1, 14, 2):
# Check for the value of i in each iteration
breakpoint()
# Bad condition
if i % 2 == 0:
n_odds += 1
print(n_odds)
Conclusion
In this tutorial, you learned:
- To choose a random element from a sequence
- To unpack elements with
*
operator - The ability of sets to deleting duplicates efficiently
- How to search for methods and variables without exiting the code editor
- The diverse uses of python slices
- How to call a debugger with the function
breakpoint
Please consider supporting me on Ko-fi. You would help me to continue building these tutorials!.
If you have any feedback please, let me know in the comments!
Read also:
Top comments (18)
Unpacking gets even better than that...
You can include one starred name among the names to unpack into. Python will fill in all the others based on position, and then stuff the rest into the starred name.
In this case, I use
_
for the name, because I really only intend to throw those away._
is a completely valid name in Python, but it's conventionally used as a "throw away" name. If you're curious, you can still see what was parked in there in the above code with...P.S. Bit of shameless self-promotion, all of the above is in my forthcoming book "Dead Simple Python" (No Starch Press, 2021). So, it isn't quite that "no one" covers this stuff.
What such an amazing explanation Jason.π€―
That's exactly why I said the unpack operator deserves an isolated article.
BTW, I'd be glad to read your book.
If you want, you can add directly here the link π
Heh, I will once I have one. It'll be this fall, tho.
Sweet, man! I didn't even know these existed!!
The * python iterator is kind of like the ES6
[...arr]
in a way.Hey! I think I know you ...
It seems Python and Js are not that different π€£
Wow, that is a really great post though! I am very surprised by those tricks and tips actually, as I did not even expect that you can do this kind of things. And, that is true, no one actually teaches you those things, which makes them even more amazing! I am learning python right now actually, and I have to tell you that most of the teachers tend to avoid from teaching us different useful tips and tricks, the only place where you could actually find these tricks are the python learning websites, nurtem.com/classes-and-camps/progr... is one of them, and probably the best one, at least the best ones.
fantastic article! i learnt many things new
Thanks for the feedback π
Nice! Some neat tips in here.
Thanks ππΌ
Great knowledge shared.. Keep up the good work
I'm glad you find it useful!
Amazing article keep it up
You can use
some_list.reverse()
also
Of course. That is a useful method,