Here are some tips and useful libraries in Python that can make your life way easier but are not well-known to most programmers.
If you need to get every possible combination of elements in a collection, permutations
function from itertools
module is your friend. It's easy to use, fast and very Pythonic.
from itertools import permutations
example_list: list = [1,2,3]
for permutation in permutations(example_list):
print(permutation)
Every permutation you'll get as a result is a tuple:
(1, 2, 3)
(1, 3, 2)
(2, 1, 3)
(2, 3, 1)
(3, 1, 2)
(3, 2, 1)
When you want to get every possible combination with a fixed-length results, you can use combinations
from the same itertools
module.
from itertools import combinations
for c in combinations([1,2,3,4], 2):
print(c)
The first argument is a collection you want to use as an input, the second is length of each combination set. So the result of the above is:
(1, 2)
(1, 3)
(1, 4)
(2, 3)
(2, 4)
(3, 4)
It might happen that you'll have to find the most common elements in a collection or multiple collections. There's an elegant solution in the collections
module that can save you a lot of time:
from collections import Counter
drama = Counter("drama")
comedy = Counter("comedy")
print((drama+comedy).most_common(3))
Et voila, here are the three most-common elements in both list:
[('d', 2), ('a', 2), ('m', 2)]
I hope you enjoyed it and learned something new. I'll be posting more bite-size articles like this in the future, so don't forget to bookmark this blog. :)