What are the parts of list comprehension?
List comprehension can be intimidating at first! So let’s break it down into its three basic parts:
- The part we want to calculate:
[x … …]
- The range of values we want to operate in:
[... for x in range(start, end) …]
- The condition, if any, that must be met:
[... … if x == some_condition]
This is the example given:
doubles_by_3 = [x * 2 for x in range(1, 6) if (x * 2) % 3 == 0]
The part being calculated is
x * 2.
The range to operate in is
for x in range(1, 6).
The condition that each
xmust meet to be used is
if (x * 2) % 3 == 0.