Module 10 · Comprehensions and Advanced Iteration — topic 1 of 13
List comprehensions
Building a new list from an iterable in a single expression: the [expression for item in iterable] form, how it compares to a for loop with append, and when a comprehension improves readability.
Learning objectives
- Write list comprehensions that transform every item
- Convert between a for-append loop and a comprehension
- Judge when a comprehension is clearer than a loop
Definition
A list comprehension is an expression of the form [expression for item in iterable] that evaluates the expression for each item and collects the results into a new list.
Introduction
A very common loop pattern creates an empty list and appends a transformed value for each item. List comprehensions express that whole pattern in one readable line: squares = [n * n for n in range(5)].
Read it from the middle outwards: for n in range(5), compute n * n, and collect the results in a list.
Why it matters
Comprehensions are one of the most characteristic features of Python; you'll see them in almost every real codebase. They are shorter than the equivalent loop, avoid off-by-one mistakes with indexes and usually run a little faster.
Detailed explanation
The general form is [expression for name in iterable]. The expression can use name and anything else in scope, including function calls and conditional expressions.
It always produces a new list; the original iterable is not changed. The new list has exactly one element per item processed.
Any iterable works as the source: lists, strings, ranges, dictionary views, files and generators.
The loop variable lives only inside the comprehension; it doesn't leak into the surrounding code.
A comprehension is equivalent to: result = []; for name in iterable: result.append(expression). If you need several statements per item, print debugging, or early exits with break, use a normal loop instead.
Keep comprehensions short — if one spans more than a line or two, a loop or a helper function is clearer.
Syntax
- Produces a new list.
- One result per item.
- The loop variable doesn't leak.
Code examples
Transforming every item
[1, 4, 9, 16, 25] ['Asha', 'Ravi', 'Meera'] [4, 4, 5]
Loop versus comprehension
[118.0, 295.0, 94.4] [118.0, 295.0, 94.4]
More examples
Comprehensions over different iterables
['P', 'Y', 'T', 'H', 'O', 'N'] [10, 20, 30, 40, 50] ['Asha=91', 'Ravi=74'] [60, 21, 20]
Step-by-step explanation
- Iterating a string visits each character.
- range(1, 6) supplies the numbers 1 to 5.
- items() yields (key, value) pairs, unpacked into name and score.
- The last comprehension iterates over a generator that splits each row; int() also ignores the space after the comma.
Expected output
Running “Comprehensions over different iterables” prints exactly:
Practical applications
- Cleaning a column of data: [s.strip().lower() for s in raw].
- Extracting a field from records: [user['email'] for user in users].
- Converting types: [int(x) for x in line.split()].
Best practices
- Use comprehensions for simple transformations and filters.
- Name the loop variable meaningfully.
- Switch to a loop when logic needs more than one expression.
Common mistakes
Comprehension for side effects
Avoid
Prefer
A comprehension builds a list; using it only for side effects creates a useless list of None values.
Over-long comprehension
Avoid
Prefer
Readability comes first; complex logic belongs in a regular loop.
Important notes
- Comprehensions are typically slightly faster than append loops because the list-building happens inside the interpreter.
Key takeaways
- [expr for x in iterable] builds a new list.
- It replaces the empty-list-and-append pattern.
- Use loops for side effects or complex logic.
Try it yourself
- 1Convert a list of Celsius temperatures to Fahrenheit with a comprehension.
- 2Build a list of the first letters of each word in a sentence.
Finished reading? Mark it complete to update your dashboard.
Suggested practice
1 question test this exact topic. Answers and explanations are revealed after you submit.
- ModerateWhat is printed?