List Comprehensions & Generators
Python · Intermediate
Definition
Comprehensions build lists/dicts/sets in one expression; generators produce values lazily with yield.
They make code shorter, faster and memory-efficient.
Diagram
Flowchart
Example: Squares of evens
print([x*x for x in range(10) if x % 2 == 0])Output: [0, 4, 16, 36, 64]
Key points
- Generators save memory
- yield pauses a function
- Avoid overly complex comprehensions
Interview questions
Generator vs list?
A generator computes items on demand and can be iterated only once.