Are python comprehensions faster than loops, why, and does it matter?

Python comprehensions are believed to be faster for generating collections than for loops. The question is why are they faster? What part of a comprehension is faster than in the loop? Below we answer this question and whether their faster performance is something worth considering. This will be more of an exploratory exercise, where the journey and methodology are more interesting than the destination. If you need only the conclusions, you can jump there....

2021-11-15 · 8 min

defaultdict: a hidden gem of Python standard library

Often you need to store data (counters, sums, lists, etc.) about some entities. A regular Python dictionary will suffice with one caveat: before adding information regarding a particular entity you need to check if the corresponding key exists in the dictionary, otherwise you will get a KeyError. Do not know about you, but I have written similar code many times: dct = {} if key not in dct: dct['key'] = 0 dct['key'] += 1 A better way While it is perfectly workable, it does not add to readability....

2021-10-25 · 2 min