187 – Anatomy of a list comprehension#
A list comprehension is made up of three sections:
Data transformation: The code that is transforming elements by applying a function or another expression to your values.
Data source: If you’re transforming data, the data must come from somewhere.
Data filter: Optionally, you can add a data filter so you’re only transforming some of the elements coming from the data source.
These three parts make up a general list comprehension. In code, it looks like this:
my_list = [
data_transformation(value) # 1
for value in data_source # 2
if predicate(value) # 3
]
Each line of the list comprehension above maps to one of the sections of a list comprehension. Here is a concrete example:
my_list = [
n ** 2 # 1
for n in range(1000) # 2
if (n % 3 == 0) or (n % 5 == 0) # 3
]
The list comprehension above
computes squares
of the integers from
0to999but only if the integer is divisible by
3or5.
Further reading:
List comprehensions 101, https://mathspp.com/blog/pydonts/list-comprehensions-101
List comprehensions cheatsheet, https://mathspp.gumroad.com/l/comprehending-comprehensions-poster