Comprehensions build lists, dicts, or sets concisely from iterables—Pythonic alternative to map/filter loops, similar spirit to LINQ in C#.
List and dict comprehensions
squares = [n * n for n in range(5)]
evens = [n for n in range(10) if n % 2 == 0]
word_len = {w: len(w) for w in ["hi", "hello"]}
Set comprehensions
unique_lengths = {len(w) for w in ["hi", "hello", "hey"]}
Keep comprehensions readable—nested or long conditions belong in regular loops for clarity.
Important interview questions and answers
- Q: Comprehension vs map?
A: Both transform iterables; comprehensions are often clearer;mapaccepts callables lazily in Python 3. - Q: Generator expression?
A:(x for x in iterable)yields lazily—memory efficient for large streams.
Self-check
- Write a comprehension for squares 0–4.
- What brackets build a dict comprehension?
Tip: Keep comprehensions readable—two nested loops often belong in a regular for loop.
Interview prep
- List vs generator expression?
List builds in memory; generator
(x for x in ...)yields lazily—better for large streams.- When not use comprehension?
Nested complex logic—plain loops improve readability for teammates.