Learn with diagrams, code, systems and practical examples.
Comprehensions
Build collections from other collections with concise, readable expressions.
Comprehensions can express simple transformations clearly when a full loop would add noise.
Start with the idea
A comprehension combines iteration, transformation, and optional filtering into one expression. Use it when the transformation remains easy to read.
Small working example
Run this example first. Do not change several things at once; confirm the basic behavior, then experiment.
numbers = [1, 2, 3, 4]
squares = [n * n for n in numbers if n % 2 == 0]
print(squares) A comprehension combines iteration, transformation, and optional filtering into one expression. Use it when the transformation remains easy to read.
- Comprehensions create collections.
- They can transform and filter.
- Readability matters more than compactness.
[4, 16]The example is intentionally small. Focus on the chapter’s main idea before adding extra syntax or framework code.
Common beginner mistake
Packing complex business logic into a long comprehension just to make code shorter.
Use a normal loop when several steps, branches, or side effects are involved.
Quick recap
- Comprehensions create collections.
- They can transform and filter.
- Readability matters more than compactness.
Try it yourself
These are deliberately small. If you can complete them without copying the example, you are ready to continue.
- Create a list of uppercase names.
- Create a dictionary mapping numbers to squares.