Python List Comprehension Explained for Beginners

Python List Comprehension Explained for Beginners


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?

Pipeline of Python list comprehension for beginners: items filtered and transformed into a new list
How a list comprehension filters and transforms items into a new list

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:

nums = [1, 2, 3, 4, 5, 6]
squares_of_even = [n * n for n in nums if n % 2 == 0]
print(squares_of_even)
Output
[4, 16, 36]

Why use list comprehensions?

Python list comprehension for beginners compared to loops: shortcut workflow versus long multi-step path
List comprehension is the shortcut compared to a long looping route
  • 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 * item or item.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)

1) Start with an iterable

e.g., nums = [1,2,3,4]

2) Take each item

for n in nums

3) Optional filter

if n % 2 == 0

4) Transform

n * n

5) Collect

build new list

Pattern: [n * n for n in nums if n % 2 == 0]

Basic transform (map) example

names = ["ali", "Bea", "carl "]
clean_upper = [name.strip().upper() for name in names]
print(clean_upper)
Output
['ALI', 'BEA', 'CARL']

Filtering example

data = [-2, -1, 0, 3, 5]
positives = [x for x in data if x > 0]
print(positives)
Output
[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

nums = [1, 2, 3, 4]
labels = ["even" if n % 2 == 0 else "odd" for n in nums]
print(labels)
Output
['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:

Code
lines = ["10n", " 20", "", "thirty", "40 "]
numbers = [int(line.strip()) for line in lines if line.strip().isdigit()]
print(numbers)
Output
[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)

matrix = [[1, 2, 3], [4, 5], [6]]
flat = [x for row in matrix for x in row]
print(flat)
Output
[1, 2, 3, 4, 5, 6]

All pairs (Cartesian product)

pairs = [(i, j) for i in [1, 2, 3] for j in [1, 2]]
print(pairs)
Output
[(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

  1. Start with a working for loop.
  2. Identify the final value that you append (that becomes the expression).
  3. Move your loop header (for item in iterable) after the expression.
  4. If you have an if filter, move it to the end.

Convert a for loop to a list comprehension (example)

Original loop:

result = []
for n in range(10):
if n % 2 == 1:
result.append(n * n)
print(result)
Output
[1, 9, 25, 49, 81]

As a list comprehension:

result = [n * n for n in range(10) if n % 2 == 1]
print(result)
Output
[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 the for), while a filter-only if goes at the end.
  • Trying to use break or continue. Comprehensions accept expressions only—no break or continue. 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 after in.

Example: scope does not leak in Python 3

nums = [1, 2, 3]
_ = [i * i for i in nums]
try:
print(i)
except NameError:
print("i is not defined")
Output
i is not defined

Example: using an assignment expression in a filter (Python 3.8+)

names = ["Ann", "Bo", "Charlie"]
long_lengths = [n for s in names if (n := len(s)) > 2]
print(long_lengths)
Output
[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:

out = []
for n in range(10):
if n % 2 == 0:
out.append(n // 2)

into:

out = [n // 2 for n in range(10) if n % 2 == 0]

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/else only 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

Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted