3 follow-up notes on 3 python list comprehension tricks

·1 min readlist-comprehensionpython

I saw the following post about list comprehension tricks in Python. I really like python comprehension functionality - dict, set, list, I don’t discriminate. So 3 follow up notes about this post -

1. Set Comprehension

Beside dictionary and lists, comprehensions also work for sets - [sourcecode language="python" wraplines="false" collapse="false"] {s for s in [1, 2, 1, 0]} #set(0,1,2)) {s**2 for s in [1,2,1,0,-1]} #set(0,1,4) [/sourcecode]

2. Filtering (and a glimpse to generators)

In order to filter a list, one can iterate over the list or generator, apply the filter function and output a list or can use the build-in filter function and receive a generator that is more efficient as described further in the original post. [sourcecode language="python" wraplines="false" collapse="false"] words = ['deified', 'radar', 'guns'] palindromes = filter(lambda w: w==w[::-1], words) list(palindromes) #['deified', 'radar'] [/sourcecode] Additional nice to know the build-in function is the map function, that for example can yield the words’ lengths as generators -  [sourcecode language="python" wraplines="false" collapse="false"] words = ['deified', 'radar', 'guns'] lengths = map(lambda w: len(w), words) list(lengths) #[7, 5, 4] [/sourcecode]

3. Generators

Another nice usage of generators is to create an infinite sequence -  [sourcecode language="python" wraplines="false" collapse="false"] def infinite_sequence(): num=0 while True: yield num num+=1 gen = infinite_sequence() next(gen) #0 next(gen) #1 next(gen) #2 [/sourcecode] Generators can be piped, return multiple outputs, and more. I recommend this postto a better understand generators.