5 Python Tricks You Should Know
5 Python Tricks You Should Know
5 Python Tricks You Should Know
Python has such an amazing support network it can almost seem like there is too much to take in
all at once. This is normal and should be recognised. It can be confusing for those starting out.
You can find vast quantities of resources to grapple with the basics but then what ? Where do
you go to keep improving?
Here, I list my top 5 useful snippets of code which I felt pushed my level up further and made my
code better. You will start to see how you can implement these five things into your code.
1. List comprehensions
You may have heard of these before. A pattern of coding in python is so common that it warrants
a modification. Any time you want to use a for loop to create a list. This is where list
comprehensions can be useful.
They are readable and concise. They do take a bit of time to wrap your head around what is going
on. Let's dive in and see if we can figure this out.
We know list comprehensions should be thought of when you want to create a list. A list
comprehension begins with a set of square brackets. Let's get the syntax out of the way and we
can show how the two are alike
new_list = []
for item in old_list:
new_list.append(item**2)
Notes
1. A list called new_list is called
2. A for loop iterates over item in old list
3. We use the append method to add item**2 to the new list
So far simple.
Thereʼs no append method or: need and this fits on one line! We can even add in conditionals, to
select what gets added. This functionality also extends to sets and dictionaries! You can even
write list comprehensions with nested for loops!
A word of caution, these can be overused! Only use a list comprehension if itʼs a simple for loop
and you explicitly want to create a list.
They create iterators that need to be forced to spit out the values it holds. They donʼt store
objects in memory like a list or a set. They only give you one item at a time too. This is called lazy
looping. So when you want to read a large file in use a generator.
def gen(n):
while True:
yield n
n += 1 G = gen(3)
print(next(G)) # 3
print(next(G)) # 4
print(next(G)) # 5
print(next(G)) # 6
Notes
1. We create a function gen
2. Yield keyword stores the value n, holds onto it till we call the next() method
3. Using the assignment operator we add to 1 to n
4. This is an infinite loop and keeps going
5. We call the next() method, and it will continue to spit out values
Now, these values arenʼt stored, and only give to us when we call the next() method. A generator
creates an iterator, which relies on the next() method then to spit out values.
This is can be useful when we have a large data set and we want to stream in data without
overloading the memory. Please see here for further details.
This steps through both objects at the same time, a tuple is returned with corresponding items
from each one. In the loop, we unpacked the tuple into separate values file_name and link.
zip() can take as many collections as you like, but will stop when the shortest one is exhausted.
Zip functions can be used to iterate over pairs of elements in the same object using a list
comprehension we spoke about.
For example:
For more information please see my articles on the zip function here.
Jake Nackos from Unsplashed
import collections
counts = Counter(['Fred', 'Samantha', 'Jean-Claude', 'Samantha'])
print(counts)
Output:
Counter({'Samantha': 2, 'Fred': 1, 'Jean-Claude': 1})
What is great about the counter class is you can update it and the values can be accessed using
the dictionary API.
Output:
a : 3
b : 2
c : 1
d : 1
e : 0
Notes
1. c assigned to the Counter subclass with string ‘abcdaabʼ. The counter class provides individual
counts of each character. Each one can be accessed like a dictionary by c[item].
2. A for loop used to iterate over string ‘abcdeʼ, and assigning letter to each string characters.
3. Prints the variable letter and like a dictionary by inputting the string character. The count for
each letter is accessed by c[letter].
More objects can be inputted by the update() met, but for this and more please see here for
further details!
Eternal Seconds from Unsplashed
Related Articles