list, set, and dict comprehensions
The Python list
, set
, and dict
comprehensions are a very easy way to apply a function or filter to a list of items.
When used correctly, list
/set
/dict
comprehensions can be really useful for quick filtering or transforming of lists, sets, and dicts. The same results can be achieved using the “functional” functions map
and filter
, but list
/set
/dict
comprehensions are often easier to use and also easier to read.
Basic list comprehensions
Let’s dive right into a few examples. The basic premise of a list
comprehension looks like this:
>>> squares = [x ** 2 for x in range(10)]
>>> squares
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
We can easily expand this with a filter:
>>> odd_squares = [x ** 2 for x in range(10) if x % 2]
>>> odd_squares
[1, 9, 25, 49, 81]
This brings us to the version that is common in most functional languages using map
and filter
:
>>>...