Python Tutorial 0/52 lessons ~6 min read Lesson 15
Comprehensions
Comprehensions let you build lists, dicts, sets in one line — faster and more readable than equivalent loops.
Course progress0%
Focus
9 guided sections
Practice signal
Examples included
Career prep
Interview Q&A included
Introduction
Comprehensions let you build lists, dicts, sets in one line — faster and more readable than equivalent loops. Beloved feature of Python.
Understanding the topic
Core concepts to understand:
- List:
[x*2 for x in xs] - Dict:
{k: v for k, v in items} - Set:
{x for x in xs} - Conditional:
[x for x in xs if x > 0]
Syntax reference
Visual flow / code:
python
# Listsquares = [x * x for x in range(10)]# With filterevens = [x for x in range(20) if x % 2 == 0]# Dict comprehensioninv = {v: k for k, v in {"a": 1, "b": 2}.items()}# Nestedmatrix = [[i * j for j in range(3)] for i in range(3)]# Set comp dedupesunique = {word.lower() for word in text.split()}
Execution workflow
1Comprehensions Workflow
1 / 4List
[x*2 for x in xs]
Real-world use
Comprehensions are the Pythonic way to transform collections. They're typically 30-50% faster than equivalent for-loops with append.
Best practices
- Prefer comprehensions over
map/filter. - Keep them one-liner readable.
- Switch to a loop when logic grows.
Common mistakes
- Nested comprehensions become unreadable — use loops instead.
Advanced interview questions
Interview Prep
Practice concise answers, then expand each card for the explanation.
1IntermediateQuestionList comp vs for-loop performance?+
Answer
A comprehension is usually somewhat faster than an equivalent loop that calls
append, because the looping and list building happen in optimized bytecode without repeated method lookups. Python 3.12 also inlines list, dict, and set comprehensions (PEP 709), removing the hidden function call. The difference is typically modest, so choose based on readability and measure with timeit if it matters.Follow-up
What did PEP 709 change?
2BeginnerQuestionWhen NOT to use a comprehension?+
Answer
Avoid them when the logic needs several statements, nested loops that hurt readability, or side effects such as printing or mutating state, since a comprehension should build a value. Also avoid them when you only need to iterate once over huge data, where a generator expression saves memory. If you have to squint at it, use a normal loop.
3BeginnerQuestionWhat's a generator comprehension?+
Answer
A generator comprehension, or generator expression, uses parentheses like
(x * x for x in data) and produces a lazy iterator instead of building a list. It computes values on demand, so memory use stays constant, and it can be consumed only once. It is handy as an argument to functions like sum, any, and max.Follow-up
Why can you iterate a generator expression only once?
Summary
In summary: Comprehensions = idiomatic Python. Stop when readability suffers.
Ready to mark this lesson complete?Track your journey across the entire course.