Hy guys!
Today I'm going to share with you the best tips and tricks to master in Python!
These tips are based on my experience on Codingame, during ClashOfCode (I was in the top 100 at one time :) )
1/ Create a number sequence
Sometimes you may want to create a sequence of numbers: a fairly intuitive way would be to create a loop and perform n calls of the append() method.
my_list = []
for i in range(0, 10, 1):
my_list.append(i)
In reality this operation is quite time consuming, and it is better to write :
my_list = list(range(0,10,1))
>>> my_list = [0,1,2,3,4,5,6,7,8,9]
This is not only faster to write but also faster to compute!
2/ Overlaying two dictionaries
Concatenating two dictionaries can be a useful operation to group information and avoid getting lost in lots of variables...
So we can use the update() method:
a = {“alpha”: 3, “beta”: 5}
b = {“gamma”: 1, “delta”: 12}
a.update(b)
>>> a = {“alpha”: 3, “beta”: 5, “gamma”: 1, “delta”: 12}
Warning: if there are two identical keys, then the value will be that of dictionary b.
3/ Create a dictionary of a sequence
By creating a dictionary of a sequence, I mean easily creating (in one line) a dictionary where the key depends on x and where the value also depends on x. However, this method can be modified to create the dictionary according to a list, inputs, etc...
my_dic = {(x+2): (x**2 + 1) for x in range(4)}
>>> my_dic = {2: 1, 3: 2, 4: 5, 5: 10}
4/ Reverse a list
Inverting a list is one of the most useful things you can do in Python. You must know this operation !
my_list = [1, 2, 3, 4]
my_list = my_list[::-1]
>>> my_list = [4, 3, 2, 1]
It is much faster to write, much more readable, and especially much faster to execute than the built-in function reversed().
5/ Unpacking a tuple
Unpacking a tuple is an interesting operation especially to perform operations on the values, and avoid having to retrieve the value by its index each time:
my_tup = (0, 1, 2, 3)
a, b, c, d = my_tup
>>> a = 0
>>> b = 1
>>> c = 2
>>> d = 3
6/ Filter a list
Filtering a list is a useful process in algorithms or in more common programs. You can keep the values you want by passing a list into a function that acts as a filter. This function returns True (the value is kept) or False (the value is deleted).
my_list = [1,2,3,4]
def my_filter(x):
if x==3 or x%2==0:
return True
else:
return False
my_list = list(filter(my_filter, my_list))
>>> my_list = [2,3,4]
7/ Return multiple values from a function
We know that to return a value from a list, we must use return. However, the function stops after returning a value. However, we can use yield to continue to execute the function. Useful for returning variables, for debugging, etc.
def my_func(x)
for i in range(x):
yield x**2
for k in my_func(4):
print(k)
>>> 0
>>> 1
>>> 4
>>> 9
8/ import this
The this library is more a joke than a trick, but it's nice to know the little easter eggs of its language:
import this
The Zen of Python
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
. . .
9/ Basic operations on sets
If we have two sets a and b such that :
a = {1,2,3}
b = {3,4,5}
then we can perform the following operations that you must know !
# Union
print(a & b)
>>> {1, 2, 3, 4, 5}
# Intersection
print(a | b)
>>> {3}
# Symetric difference
print(a ^ b)
>>> {1, 2, 4, 5}
10/ Code if : else : in one line
It's not the most useful trick, but it's always useful to know how to write an if : else : in one line to make the code cleaner, or in shortest code competitions on codingame !
i = 1 if True else 2
>>> i = 1
11/ Limit the number of recursion of an algorithm
Limiting the depth of recursion of an algorithm is important. It is even the first thing to do when you know the maximum depth of recursion! You can do it with the Python library sys:
import sys
sys.setrecursionlimit(1000)
12/ Print text faster
When we have to print text in Python, we use by default the print() method ! However, when you have to print thousands of lines, this method can be slow. In this case we use :
import sys
sys.stdout.write(…) # only string
You can use a similar method for the input, but it's a bit more complex :)
This method is up to 8 times faster than the normal print
13/ Have the middle items of a list
Having the items in the middle of a list is a little trick to know when unpacking this list... Indeed, depending on the number of variables (or underscore if you don't want to keep the variable) at the beginning and at the end, you can have a variable containing a list of values containing only the "middle" one, in fact, the one that have not been put in other variables!
l = [1,2,3,4,5,6,7]
a, *b, c = l
>>> a = 1
>>> b = [2,3,4,5,6]
>>> c = 7
14/ Separate big numbers by _
For more readability, and because Python does not allow spaces between the digits of a number, we can use _. For example, 1 000 000 000 can be written in Python :
1_000_000_000
15/ Exchange keys / values of a dictionary
Exchanging the keys and values of a dictionary is a technique that can be useful, especially in the field of AI :). Here is how to do it:
my_dic = {“a”: 1, “b”: 2}
my_dic = {v:k for k, v in my_dic.items()}
my_dic = {1: “a”, 2: “b”}
Conclusion
That's all for today, I hope you liked the article and that you were able to improve your coding skills! Don't hesitate to share the article with your friends and to give me your feedback in comments!
Adrien