Tutorials Python Python List Comprehension
Ch 23 / 58
Python Intermediate 10 min read Chapter 23 of 58

Python List Comprehension

List comprehension is one of Python's most iconic features — a compact, elegant way to build a new list from an existing iterable in a single, readable expression. Instead of writing a multi-line for loop, appending results one by one, you describe what you want in one line: [expression for item in iterable if condition]. This chapter covers the complete syntax with an anatomy diagram, filtering, nested comprehensions, conditional expressions (ternary), performance insights, and real-world patterns used in professional Python code.

What you'll learn in this chapter
List comprehension syntax with anatomy diagram
Basic transformation: apply expression to each item
Filtering with the if clause
Ternary (if-else) inside comprehension
Nested list comprehensions
When to use vs when to avoid comprehensions
Advertisement

Syntax & Anatomy

A list comprehension is enclosed in square brackets [] and contains up to three parts: an expression, a for clause, and an optional if clause for filtering. The diagram below shows every part labelled:

List Comprehension — Syntax Anatomy
[
open
 
expression
what to put
→
for item in iterable
source of data
→
if condition
optional filter
 
]
close
Example: [x**2 for x in range(10)]
With filter: [x**2 for x in range(10) if x % 2 == 0]
Python — lc_syntax.py
# Syntax: [expression for item in iterable if condition]

# Traditional for loop
squares_loop = []
for x in range(6):
    squares_loop.append(x**2)
print(squares_loop)   # [0, 1, 4, 9, 16, 25]

# Equivalent list comprehension — one line!
squares_lc = [x**2 for x in range(6)]
print(squares_lc)    # [0, 1, 4, 9, 16, 25]

# Returns a LIST — always enclosed in []
print(type(squares_lc))  # <class 'list'>

# Iterable can be any iterable — string, range, list, tuple...
chars = [c.upper() for c in "python"]
print(chars)         # ['P', 'Y', 'T', 'H', 'O', 'N']
How Python evaluates a list comprehension Python reads it right-to-left internally: first it iterates the iterable, then for each item checks the optional condition, then applies the expression and appends the result to a new list. The final result is always a brand new list object.

Basic Transformation Examples

The simplest list comprehension applies a transformation to every element of an iterable — no filter, just one expression applied across all items.

Python — lc_basic.py
# Multiply each number by 2
doubled = [x * 2 for x in range(1, 6)]
print(doubled)        # [2, 4, 6, 8, 10]

# Cube numbers 1-5
cubes = [x**3 for x in range(1, 6)]
print(cubes)          # [1, 8, 27, 64, 125]

# Apply string method to each item
fruits = ["apple", "banana", "cherry"]
upper  = [f.upper() for f in fruits]
print(upper)          # ['APPLE', 'BANANA', 'CHERRY']

# Get lengths of each word
words   = ["Python", "is", "awesome"]
lengths = [len(w) for w in words]
print(lengths)        # [6, 2, 7]

# Convert string digits to integers
str_nums = ["1", "2", "3", "4"]
int_nums = [int(n) for n in str_nums]
print(int_nums)       # [1, 2, 3, 4]

# Extract attribute from list of objects/tuples
students = [("Alice", 90), ("Bob", 85), ("Carol", 92)]
names    = [name for name, _ in students]
scores   = [score for _, score in students]
print(names)          # ['Alice', 'Bob', 'Carol']
print(scores)         # [90, 85, 92]

Filtering with the if Clause

Adding an if condition after the for clause filters which items are included. Only items for which the condition is True pass through — the rest are silently skipped.

Python — lc_filter.py
# Only even numbers from 1–20
evens = [x for x in range(1, 21) if x % 2 == 0]
print(evens)
# [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]

# Squares of even numbers only
even_squares = [x**2 for x in range(1, 11) if x % 2 == 0]
print(even_squares)   # [4, 16, 36, 64, 100]

# Filter strings by length
words      = ["hi", "Python", "is", "awesome", "go"]
long_words = [w for w in words if len(w) > 3]
print(long_words)     # ['Python', 'awesome']

# Skip empty / None values
data  = ["Alice", "", "Bob", None, "Carol", "  "]
valid = [item for item in data if item and item.strip()]
print(valid)          # ['Alice', 'Bob', 'Carol']

# Multiple conditions with and/or
nums  = range(1, 50)
result= [n for n in nums if n % 3 == 0 and n % 5 == 0]
print(result)         # [15, 30, 45]  — divisible by both 3 and 5

# Filter and transform together
positives = [-3, 2, -1, 4, -5, 6]
doubled_pos = [x * 2 for x in positives if x > 0]
print(doubled_pos)    # [4, 8, 12]
Advertisement
K2infocom Python Masterclass & Backend Development
Master Python, Django & Backend APIs with AI
Go from absolute beginner to building production-ready REST APIs, web applications, and ML pipelines. Real projects, live mentoring in Vadodara, and placement support included.
2,400+
Students Enrolled
4.9 ⭐
Google Rating
6 Months
Full Program
100%
Placement Support
Python 3 Django & DRF FastAPI PostgreSQL Machine Learning Docker & AWS Real Projects AI Tools

Conditional Expression (if-else / Ternary) in the Expression Part

A ternary expression (value_if_true if condition else value_if_false) can be placed in the expression part — the section before the for. This transforms every element conditionally, unlike the filter if (which sits after for and removes elements).

Filter if vs Ternary if-else — key difference [x for x in lst if x>0] — the if is a filter; items that don't pass are dropped from the result.
["pos" if x>0 else "neg" for x in lst] — the if-else is in the expression; every item produces a result.
Python — lc_ternary.py
# Label each number as "even" or "odd"
labels = ["even" if x % 2 == 0 else "odd"
          for x in range(1, 7)]
print(labels)
# ['odd', 'even', 'odd', 'even', 'odd', 'even']

# Replace negatives with 0
nums    = [-3, 2, -1, 4, -5, 6]
clipped = [x if x >= 0 else 0 for x in nums]
print(clipped)          # [0, 2, 0, 4, 0, 6]

# Absolute value using ternary
absolutes = [x if x >= 0 else -x for x in nums]
print(absolutes)        # [3, 2, 1, 4, 5, 6]

# Assign "pass"/"fail" grade
scores = [45, 72, 38, 91, 60]
grades = ["pass" if s >= 50 else "fail" for s in scores]
print(grades)           # ['fail', 'pass', 'fail', 'pass', 'pass']

# Ternary + filter (both in one comprehension)
# Only process positive; replace negatives that do pass through
values  = [-2, 5, -1, 8, 3]
result  = [x * 10 if x > 3 else x for x in values if x > 0]
print(result)           # [50, 80, 3]  — negatives filtered, >3 multiplied

Nested List Comprehensions

You can nest multiple for clauses in a single comprehension — the leftmost for is the outer loop and subsequent ones are inner loops (same order as nested for loops written out). This is great for flattening 2D structures or generating Cartesian products.

Python — lc_nested.py
# ── Flatten a 2D matrix ─────────────────────────────
matrix = [[1,2,3], [4,5,6], [7,8,9]]
flat = [n for row in matrix for n in row]
print(flat)     # [1, 2, 3, 4, 5, 6, 7, 8, 9]

# Equivalent nested loops:
# for row in matrix:
#     for n in row:
#         flat.append(n)

# ── Cartesian product ────────────────────────────────
colours = ["red", "green"]
sizes   = ["S", "M", "L"]
combos  = [(c, s) for c in colours for s in sizes]
print(combos)
# [('red','S'),('red','M'),('red','L'),('green','S')...]

# ── Transposing a matrix ─────────────────────────────
matrix    = [[1,2,3], [4,5,6]]
transposed= [[row[i] for row in matrix] for i in range(3)]
print(transposed)  # [[1, 4], [2, 5], [3, 6]]

# ── Nested with filter ────────────────────────────────
pairs = [(x, y) for x in range(1, 5)
               for y in range(1, 5)
               if x != y]
print(pairs[:6])   # [(1,2),(1,3),(1,4),(2,1),(2,3),(2,4)]
Keep nested comprehensions readable If your comprehension exceeds one line, split it across lines at each clause. If it's genuinely complex (3+ loops, complex conditions), switch to a regular for loop — readability beats brevity.

List Comprehension vs for Loop

List comprehensions are generally faster than equivalent for loops because CPython optimises them internally. But speed is not always the primary reason to choose them — readability and intent matter more.

Scenario Use Why
Build a new list by transforming items
List comprehension
Concise, fast, readable
Build a new list with a simple filter
List comprehension
Single expression fits one line
Complex multi-step logic
for loop
Better readability and debugging
Side effects (print, file write, DB call)
for loop
Comprehensions should not cause side effects
Large dataset — memory matters
Generator expression
(x for x in ...) is lazy, saves memory
Python — lc_vs_loop.py
# ✅ Comprehension — clean, concise, fast
squares = [x**2 for x in range(10)]

# ✅ for loop — better when logic is complex
result = []
for x in range(10):
    processed = x ** 2
    if processed > 5:
        processed = round(processed ** 0.5, 2)
        result.append(processed)
    else:
        result.append(0)

# ❌ Comprehension for side effects — AVOID
# [print(x) for x in range(5)]  ← works but bad style
# Use a regular loop instead:
for x in range(5):
    print(x)

# Generator expression — lazy evaluation (memory efficient)
gen = (x**2 for x in range(1000000))  # ← uses () not []
print(next(gen))    # 0 — items generated on demand
print(sum(gen))     # sum without storing all in memory

Real-World Patterns

List comprehensions appear constantly in professional Python code. Here are the most common patterns you'll encounter in real projects:

Python — lc_real_world.py
# ── 1. Extract field from list of dicts (JSON parsing) ──
users = [
    {"name": "Alice", "age": 25},
    {"name": "Bob",   "age": 30},
    {"name": "Carol", "age": 22},
]
names = [u["name"] for u in users]
print(names)            # ['Alice', 'Bob', 'Carol']

# ── 2. Filter by field value ───────────────────────────
adults = [u["name"] for u in users if u["age"] >= 25]
print(adults)           # ['Alice', 'Bob']

# ── 3. Remove duplicates preserving order ─────────────
seen    = set()
numbers = [1, 2, 2, 3, 1, 4, 3]
unique  = [x for x in numbers
            if x not in seen and not seen.add(x)]
print(unique)           # [1, 2, 3, 4]

# ── 4. Parse CSV-like string data ─────────────────────
raw    = "10, 20, 30, 40, 50"
parsed = [int(x.strip()) for x in raw.split(",")]
print(parsed)           # [10, 20, 30, 40, 50]

# ── 5. Build file paths ───────────────────────────────
filenames = ["report", "summary", "data"]
paths     = [f"/exports/{fn}.csv" for fn in filenames]
print(paths)
# ['/exports/report.csv', '/exports/summary.csv', '/exports/data.csv']

# ── 6. Find primes with comprehension ─────────────────
primes = [n for n in range(2, 50)
           if all(n % d != 0 for d in range(2, n))]
print(primes)
# [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]

Practice Python Online — Free Compilers

Don't want to install anything yet? Practice all list comprehension examples from this chapter directly in your browser with these free Python environments.

▶
Online Python 3 Compiler
Write, run and debug Python code in your browser. No installation required. Test every comprehension example instantly.
Open Compiler
Replit
Full IDE online
Google Colab
Free GPU notebooks
JupyterLite
Notebooks in browser
Programiz
Beginner-friendly
Chapter Summary
  • List comprehension syntax: [expression for item in iterable if condition] — always returns a new list.
  • The expression part (before for) defines what goes into the result. The for clause iterates the source. The if clause (optional) filters items.
  • The filter if (after for) removes items that don't pass. The ternary if-else (in the expression) transforms every item — nothing is dropped.
  • Multiple for clauses create nested loops — leftmost is outermost. Use for flattening 2D structures or Cartesian products.
  • List comprehensions are faster than equivalent loops and more readable for simple transformations and filters.
  • Avoid comprehensions when the logic is complex (use a loop) or when you just need side effects (printing, writing) — loops communicate that intent better.
  • For very large datasets, use a generator expression (x for x in ...) — it generates items lazily and doesn't store the whole list in memory.
  • Common professional patterns: extract dict fields, filter records, remove duplicates, parse strings, build file paths, find primes.
⚡
Free Resource
Download our Python List Comprehension Cheat Sheet
Syntax, filter, ternary, nested, generator expressions & real-world patterns — one printable page.
Get Sheet
Advertisement
Quick Check — Test Your Understanding
Question & Answer
✓ Answer

The full syntax is: [expression for item in iterable if condition]

  • expression — the value to include in the result list (applied to each item).
  • for item in iterable — iterates the source; item is the loop variable.
  • if condition (optional) — filters; only items where the condition is True are processed.

The result is always a new list.

✓ Answer

Filter if appears after the for clause. It decides whether an item is included at all. Items that fail the condition are dropped:

[x for x in range(5) if x > 2]  # [3, 4]  — 0,1,2 dropped

Ternary if-else appears in the expression part (before for). Every item produces a result — nothing is dropped, just transformed differently:

["big" if x > 2 else "small" for x in range(5)]
# ['small','small','small','big','big']  — all 5 items
✓ Answer

Use two for clauses — the first iterates over the rows, the second iterates over each element within a row:

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

The order of for clauses in a comprehension mirrors the order of for loops written out longhand.

✓ Answer

Avoid list comprehensions in these situations:

  • Complex multi-step logic — if the expression or condition requires multiple operations, a regular loop is clearer and easier to debug.
  • Side effects — never use comprehensions just to call print(), write to a file, or make DB calls. Use a for loop instead.
  • Very large datasets — comprehensions build the entire list in memory. Use a generator expression (x for x in ...) to process lazily.
  • Deep nesting — 3+ nested for loops in a comprehension is almost impossible to read. Break it into loops.
✓ Answer

A generator expression uses parentheses () instead of square brackets []. It has identical syntax but behaves differently:

  • A list comprehension evaluates immediately and stores all results in memory as a list.
  • A generator expression is lazy — it generates values one at a time on demand. No full list is stored, so it uses far less memory for large datasets.
lc_sum  = sum([x**2 for x in range(1000000)])  # list in memory
gen_sum = sum(x**2  for x in range(1000000))   # lazy, no list
MCQ 1 of 3
What does [x**2 for x in range(4) if x % 2 == 0] return?
MCQ 2 of 3
What is the output of ["yes" if x > 2 else "no" for x in range(5)]?
MCQ 3 of 3
Which syntax creates a generator expression instead of a list?

Rate Us on Google

4.8 / 5
Enjoying this tutorial?
Your 5-star review helps other learners discover our free tutorials and encourages us to keep creating quality content.
80+ reviews
Write a Google Review
Join WhatsApp Channel