List comprehensions are a beginner-friendly superpower in Python. They let you build new lists from existing data in a short, readable way. In this simple guide to Python list comprehension for beginners, you’ll learn what they are, why they’re useful, the syntax, common patterns (filtering, mapping, if/else, and nesting), and how to convert a regular for loop into a clean list comprehension. If you’re new to Python, you can also follow along with more lessons on our Python tutorials page.
What is list comprehension in Python?
A list comprehension is a concise expression that creates a new list from an iterable (like a list, range, file, or string). The most common form is:
[expression for item in iterable if condition]
It reads left-to-right: take each item from the iterable, keep it only if the optional condition is true, and compute the expression to produce elements for the new list.
Quick example
Create a list of squares of even numbers:
squares_of_even = [n * n for n in nums if n % 2 == 0]
print(squares_of_even)
[4, 16, 36]Why use list comprehensions?
- They’re concise and often easier to read for simple transformations.
- They reduce boilerplate (fewer lines, fewer chances for small mistakes).
- They’re great for common beginner tasks like filtering numbers, cleaning strings, and flattening small lists.
- In modern Python (3.12+), comprehensions are often faster than equivalent pure-Python loops thanks to PEP 709. Treat speed as a bonus—prefer clarity first.
Syntax explained step by step
The basic pattern is:
[expression for item in iterable if condition]
- expression: what to put in the new list (e.g.,
item * itemoritem.strip()). - for item in iterable: where values come from (e.g., a list,
range(10), or a file). - if condition (optional): filter to select items (e.g.,
if item > 0).
Flow of a Python list comprehension (beginner view)
[n * n for n in nums if n % 2 == 0]
Basic transform (map) example
clean_upper = [name.strip().upper() for name in names]
print(clean_upper)
['ALI', 'BEA', 'CARL']Filtering example
positives = [x for x in data if x > 0]
print(positives)
[3, 5]If else in Python list comprehension
You can use if/else inside the expression part to choose what to put in the new list. This is a conditional expression (ternary):
[expr_if_true if condition else expr_if_false for item in iterable]
Example: label numbers as odd/even
labels = ["even" if n % 2 == 0 else "odd" for n in nums]
print(labels)
['odd', 'even', 'odd', 'even']Filter vs inline if
- Filter with if keeps only items that match the condition:
[x for x in nums if x % 2 == 0]produces only evens. - Inline if keeps all items but changes values depending on a condition:
[x if x % 2 == 0 else 0 for x in nums].
Filter and map with list comprehension in Python
Comprehensions can do both filtering and transforming in one readable line. For example, clean lines and convert to integers, skipping invalid entries:
lines = ["10n", " 20", "", "thirty", "40 "]
numbers = [int(line.strip()) for line in lines if line.strip().isdigit()]
print(numbers)[10, 20, 40]Nested list comprehension in Python
You can add extra for clauses to combine or flatten iterables. The evaluation order is left-to-right.
Flatten a matrix (list of lists)
flat = [x for row in matrix for x in row]
print(flat)
[1, 2, 3, 4, 5, 6]All pairs (Cartesian product)
print(pairs)
[(1, 1), (1, 2), (2, 1), (2, 2), (3, 1), (3, 2)]Tip: If the nesting starts to look complicated, switch to regular loops for readability.
List comprehension vs for loop in Python
Both can do the same job. Choose the one that is easiest to read and maintain.
| Aspect | List Comprehension | For Loop |
|---|---|---|
| Readability | Great for short, simple transforms/filters | Better for multi-step or complex logic |
| Lines of code | Usually fewer | More setup (append, variables) |
| Speed | Often faster in modern Python (3.12+), but not always | Sometimes slower; depends on workload |
| Memory | Builds a full list eagerly | Also builds a list if you append; can stream with loops |
| Best use | Simple map/filter, small-to-medium data | Complex logic, side effects, early breaks |
How to write a list comprehension step by step
- Start with a working for loop.
- Identify the final value that you append (that becomes the expression).
- Move your loop header (
for item in iterable) after the expression. - If you have an
iffilter, move it to the end.
Convert a for loop to a list comprehension (example)
Original loop:
for n in range(10):
if n % 2 == 1:
result.append(n * n)
print(result)
[1, 9, 25, 49, 81]As a list comprehension:
print(result)
[1, 9, 25, 49, 81]Common mistakes with Python list comprehensions
- Placing if/else in the wrong spot. Remember: inline
if ... else ...goes in the expression part (before thefor), while a filter-onlyifgoes at the end. - Trying to use break or continue. Comprehensions accept expressions only—no
breakorcontinue. Use a regular loop for early exits. - Overly complex expressions. If you need multiple steps or nested conditions, a normal for loop is clearer.
- Assuming loop variables leak. In Python 3, the loop variable inside a comprehension does not leak into the outer scope.
- Using assignment expressions (
:=) incorrectly. They’re allowed in some parts of comprehensions (Python 3.8+), but not everywhere—for example, not directly in the iterable afterin.
Example: scope does not leak in Python 3
_ = [i * i for i in nums]
try:
print(i)
except NameError:
print("i is not defined")
i is not definedExample: using an assignment expression in a filter (Python 3.8+)
long_lengths = [n for s in names if (n := len(s)) > 2]
print(long_lengths)
[3, 7]Performance notes (modern Python)
In Python 3.12+, comprehensions may be inlined under the hood (What’s New in 3.12, PEP 709), which often makes them faster than an equivalent pure-Python loop. However, performance depends on your data and operations—use comprehensions for clarity, and treat speed as a bonus, not a promise.
List comprehensions vs generator expressions
List comprehensions ([]) build the entire list immediately. Generator expressions (()) create a lazy iterator that produces items on demand. Use a list comprehension when you need the whole list now (e.g., indexing, len). Use a generator when you want to stream values or avoid holding everything in memory. They look similar, but their behavior and memory usage differ.
| Aspect | List Comprehension [] | Generator Expression () |
|---|---|---|
| Evaluation | Eager: builds full list now | Lazy: produces items on demand |
| Memory | Holds all items | Holds one item at a time |
| When to use | Need full list (indexing, length, reuse) | Streaming, large data, pass to consumers (e.g., sum, any) |
| Example | [x * x for x in nums] |
(x * x for x in nums) |
Practice ideas
- From a list of words, build a list of word lengths for words of length ≥ 4.
- From a nested list of integers, produce a flat list of squares for the positive numbers only.
- Read lines from a file and collect only those that contain “ERROR”, stripping trailing newlines.
FAQ: Python list comprehension for beginners
What is a list comprehension in Python for beginners?
It’s a short, readable expression that builds a new list from an existing iterable by optionally filtering items and transforming them. Syntax: [expression for item in iterable if condition].
How do I convert a for loop to a list comprehension?
Move the value you append into the expression spot, keep the for clause, and put any if filter at the end. For example, turn:
for n in range(10):
if n % 2 == 0:
out.append(n // 2)
into:
Can I use if and else in a Python list comprehension?
Yes, use a conditional expression in the expression spot: [a if cond else b for x in items]. For filtering only, use a trailing if: [x for x in items if cond].
Are list comprehensions faster than for loops in Python?
Often, especially in Python 3.12+ due to comprehension inlining (PEP 709). But not always—the real speed depends on what your expression does. Choose readability first; consider speed a nice bonus.
How do nested list comprehensions work with simple examples?
Add more for clauses left-to-right. Example: flatten [[1, 2], [3]] with [x for row in matrix for x in row]. Keep nesting shallow for readability.
Beginner checklist: write clean Python list comprehensions
- ✔ Keep it simple: one clear transform and/or one filter.
- ✔ Put the filter at the end:
[x for x in xs if cond]. - ✔ Use inline
if/elseonly in the expression part:[a if cond else b for x in xs]. - ✔ Switch to a normal loop if logic gets long, has side effects, or needs
break/continue. - ✔ Prefer generators
(...)for large data you don’t need all at once. - ✔ Name loop variables clearly (e.g.,
row,word,num). - ✔ Test with a tiny sample list first to verify output.
Summary
List comprehensions are one of the most useful tools in beginner-friendly Python. They help you write clean, expressive code for common data tasks: transforming, filtering, and even combining lists. Start with simple patterns, prefer clarity over cleverness, and use regular loops if the logic gets long or tricky. Continue learning with more beginner tutorials on our Python page.
Sources / Further reading
- Python Tutorial – Data Structures (List Comprehensions)
- Python Language Reference – Expressions (Comprehensions)
- What’s New in Python 3.12 – PEP 709: Comprehension inlining
- PEP 709 – Inlined Comprehensions
- PEP 202 – List Comprehensions
- PEP 572 – Assignment Expressions
- Google Python Style Guide
- Real Python – Python List Comprehension: Tutorial With Examples


