List Comprehensions
Write concise list transformations. Read the lesson first, then move through the exercises in order.
After reading
Practice Arena
Begin with the first exercise, then continue step by step through the module.
Start with Standardizing InputStudy Material
Read the full lesson
What a list comprehension is
A list comprehension is a short way to build a new list from an existing one. It is often clearer than a long loop when the logic is simple.
The basic pattern
pythonsquares = [x ** 2 for x in range(1, 6)] print(squares)
This means: take each number, square it, and collect the results in a new list.
Filtering with an if condition
You can keep only the items that pass a test.
pythonnums = [1, 2, 3, 4, 5, 6] evens = [x for x in nums if x % 2 == 0] print(evens)
Transforming text
Comprehensions work with strings too.
pythonword = "python is fun" vowels = [ch for ch in word if ch in "aeiou"] print(vowels)
Nested comprehensions (flattening)
You can flatten a list of lists in one line.
pythonmatrix = [[1, 2], [3, 4]] flat = [num for row in matrix for num in row] print(flat)
When not to use a comprehension
If the logic is complex or hard to read, use a normal loop. Clarity is more important than short code.
Common mistakes to avoid
- Forgetting the order:
for row in matrix for num in rowis different from the other way around. - Trying to use a comprehension for side effects like printing.
- Making a comprehension so long that it is hard to understand.
What you should understand after this lesson
- The basic comprehension pattern.
- How to filter items with
if. - How to build new lists from existing data quickly.
Interactive
Exercises for this topic
These exercises follow the exact order of the lesson. Move step-by-step from reading into coding.
Standardizing Input
Use a list comprehension to format a list of user inputs.
Conditional Extraction
Form a sub-sequence exploiting filtering expressions within comprehensions.
Matrix Flattening
Grasp the nested loops of comprehensions.
Tuple Mapping
Restructure list objects into tuple components in single-liners.
Complex Transformation
Apply function modifications during list comprehensions over structured objects.