PY-101 ยท Collections
Comprehensions
โฑ 8 min ๐ Real Python 3 ๐ฌ Animated โ Completed
โก The 30-second answer
A comprehension builds a new list, dict or set from another collection in one line: [x * 2 for x in nums]. Add if at the end to keep only some items: [x for x in nums if x > 0]. It replaces the common pattern of an empty list, a loop and append.
- Write a list comprehension
- Filter with if
- Build dicts and sets the same way
Try it
Watch it come alive, run it yourself, then prove it. Real Python, right on this page.
Watch Python run the example. Every variable is a jar; watch the values change and the output appear.
prices = [100, 250, 40]with_tax = [round(p * 1.18) for p in prices]print(with_tax)cheap = [p for p in prices if p < 200]print(cheap)squares = {n: n * n for n in range(1, 4)}print(squares)
Change anything and press Run (or Ctrl+Enter). Then open Watch it and press Watch my code.
Input one line per input() call
Press Run to see the output. Python runs in your browser. Expected output
[118, 295, 47]
[100, 40]
{1: 1, 2: 4, 3: 9} ๐ฏ Use one list comprehension to make a list of the lengths of the words that have more than 3 letters. Print it.
Input one line per input() call
Press Run to see the output. Python runs in your browser. Need a hint?
lengths = [len(w) for w in words if len(w) > 3]
- The problemYou have 500 prices and need them all with 18% tax added. The loop takes four lines; a comprehension says it in one, and reads like the sentence you just said.
- The Python idea
[expr for x in items if condition]A comprehension builds a new list, dict or set from another collection in one line: [x * 2 for x in nums]. - In real lifeData pipelines clean thousands of rows with lines like emails = [e.strip().lower() for e in raw if "@" in e].
Start with a question
You have 500 prices and need them all with 18% tax added. The loop takes four lines; a comprehension says it in one, and reads like the sentence you just said.
Data cleaning and transformation are everywhere, and comprehensions are the idiomatic Python way to do them.
Explain it like I'm 10
It is like telling a helper: "for every apple in this basket, give me a sliced apple, but only the red ones". One instruction, a whole new basket.
The technical explanation
[expression for item in iterable] runs expression for each item and collects the results.
[x for x in nums if x % 2 == 0] keeps only the items where the condition is True.
{k: v for k, v in pairs} builds a dict; {x for x in items} builds a set.
Syntax
[expr for x in items if condition]
{key: value for x in items} Real-world scenario
Data pipelines clean thousands of rows with lines like emails = [e.strip().lower() for e in raw if "@" in e].
Test yourself
5 questions. Get 4 right and this lesson is marked complete.
Pass the quiz to complete this lesson.
๐ Every lesson counts toward your certificate Next: Unpacking โQuestions people ask
Are list comprehensions faster than for loops?
Usually a little, because the appending happens inside Python itself. Choose them mainly because they are shorter and clearer for simple transformations.
What is a generator expression?
The same syntax with round brackets, (x * 2 for x in nums). It produces values one at a time instead of building the whole list, which saves memory.
Interview questions
How this topic comes up in Python interviews. Answer out loud first, then open the model answer.
beginner Are list comprehensions faster than for loops?
Usually a little, because the appending happens inside Python itself. Choose them mainly because they are shorter and clearer for simple transformations.
beginner What is a generator expression?
The same syntax with round brackets, (x * 2 for x in nums). It produces values one at a time instead of building the whole list, which saves memory.
intermediate [n * 10 for n in [1, 2]]?
[10, 20]. Each item times 10.
intermediate [n for n in range(6) if n % 2 == 0]?
[0, 2, 4]. Even numbers from 0 to 5.
Quick revision
Remember
- Write a list comprehension
- Filter with if
- Build dicts and sets the same way
- If a comprehension needs more than one if or a nested loop to read, switch back to a normal loop. Clear beats clever.
Syntax
[expr for x in items if condition]
{key: value for x in items} Official documentation
- List comprehensions (docs.python.org)