Intermediate 8 min
List and dictionary comprehensions
A comprehension builds a new collection by describing what to produce from each item.
How it works
Read the loop clause before the expression. Take the next item from values, ask whether it passes the condition, then add the transformed result. The sample checks -2, 1, 0, and 3 in that order. Only 1 and 3 reach the doubling step.
Walk through an example
[n * 2 for n in values if n > 0] starts with a value, checks whether it is positive, and doubles it only when the check passes.
What to watch for
Break complicated transformations into named steps. Nesting several loops and tests in one comprehension can hide what each output depends on.
Code example
values = [-2, 1, 0, 3]
print([n * 2 for n in values if n > 0])Check your understanding
What does the positive-values doubling example produce?
See the example and explanation
- Worked example
- Given
[-2, 1, 0, 3] - Answer
[2, 6]
The values 1 and 3 are positive. They become 2 and 6 in the original order.