PythonCollectionsbeginner

Python List Comprehension with Examples

Python list comprehension from the basic form to if else and nested loops, with results and practice questions.

Published
TL;DR – Quick Answer

A Python list comprehension builds a list in one line: [expression for item in iterable if condition]. Put if at the end to drop items. Put if else before the for to choose between two values for every item.

On This Page

A Python list comprehension is a short way to build a list from another sequence. You write the loop, the value you want and an optional test inside one pair of square brackets.

This page starts with the basic form, then adds if, if else and nested loops. Each example shows its result. If loops are new to you, read the Python basics tutorial first.

Python list comprehension syntax

The full Python list comprehension syntax is:

[expression for item in iterable if condition]
Part Meaning Needed?
expression The value to put in the new list Yes
for item in iterable The loop Yes
if condition Keep only items that pass No

Compare a normal loop with the short form.

squares = []
for n in range(1, 6):
    squares.append(n * n)
print(squares)  # [1, 4, 9, 16, 25]
squares = [n * n for n in range(1, 6)]
print(squares)  # [1, 4, 9, 16, 25]

Both give the same list. The second has no empty list and no append.

How to read it

Start at the for, not at the left. "For each n from 1 to 5, take n * n." After a few days this becomes natural.

Basic Python list comprehension examples

These Python list comprehension examples have no condition.

names = ["asha", "ravi", "meena"]

print([name.title() for name in names])
# ['Asha', 'Ravi', 'Meena']

print([len(name) for name in names])
# [4, 4, 5]

print([ch for ch in "code"])
# ['c', 'o', 'd', 'e']

You can loop over any iterable: a list, string, range, dictionary or file.

marks = {"Asha": 82, "Ravi": 67}

print([f"{name}: {score}" for name, score in marks.items()])
# ['Asha: 82', 'Ravi: 67']

nums = ["10", "20", "30"]
print(sum([int(x) for x in nums]))
# 60

The last line turns text into numbers, which is useful when you read input from a user.

line = "4 8 15"
values = [int(x) for x in line.split()]
print(values)
# [4, 8, 15]

In a real program, line would come from input().

Python list comprehension with if

Put the if at the end when you want to filter. Items that fail the test are left out.

numbers = [4, 7, 10, 13, 16]

print([n for n in numbers if n % 2 == 0])
# [4, 10, 16]

words = ["data", "", "python", ""]
print([w for w in words if w])
# ['data', 'python']

The second example drops empty strings because an empty string counts as false.

You can join tests with and or or:

print([n for n in range(1, 31) if n % 2 == 0 and n % 5 == 0])
# [10, 20, 30]

You can also write two if parts one after the other. They act like and:

print([n for n in range(1, 31) if n % 2 == 0 if n % 5 == 0])
# [10, 20, 30]

The first version is easier to read, so prefer it.

Python list comprehension with if else

Put if else at the start when you want to change every item instead of dropping some.

marks = [82, 35, 91, 28]

print(["Pass" if m >= 40 else "Fail" for m in marks])
# ['Pass', 'Fail', 'Pass', 'Fail']

Four marks went in and four results came out. This is the key difference.

You want to Form Length of result
Drop some items [x for x in data if test] Same or shorter
Choose between two values [a if test else b for x in data] Always the same
Do both [a if t1 else b for x in data if t2] Same or shorter

Here is the last form. It skips missing marks, which are stored as None:

marks = [82, None, 35]

print(["Pass" if m >= 40 else "Fail" for m in marks if m is not None])
# ['Pass', 'Fail']

Common mistake: Writing [x for x in data if x > 0 else 0]. This is a SyntaxError. An else is not allowed in the filter at the end. Move the whole if else before the for.

There is no elif here. You can chain conditions, but it gets hard to read:

def grade(m):
    if m >= 75:
        return "A"
    if m >= 40:
        return "B"
    return "F"

print([grade(m) for m in [82, 55, 20]])
# ['A', 'B', 'F']

A small function keeps the list comprehension clean.

Python list comprehension nested for loop

You can use more than one for. The order is the same as in normal nested loops: outer loop first, inner loop second.

matrix = [[1, 2, 3], [4, 5, 6]]

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

The same Python list comprehension nested for loop written the long way:

flat = []
for row in matrix:
    for x in row:
        flat.append(x)

Notice that the two for parts stay in the same order.

sizes = ["S", "M"]
colors = ["red", "blue"]

print([f"{c}-{s}" for c in colors for s in sizes])
# ['red-S', 'red-M', 'blue-S', 'blue-M']

A list comprehension inside another

When the expression is itself a comprehension, you get a list of lists. This builds a grid:

table = [[r * c for c in range(1, 4)] for r in range(1, 4)]
print(table)
# [[1, 2, 3], [2, 4, 6], [3, 6, 9]]

And this turns rows into columns:

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

Interview note: Interviewers like the difference between [x for row in m for x in row] and [[x for x in row] for row in m]. The first gives one flat list. The second keeps the rows.

Dictionary, set and generator forms

The same idea works with other brackets.

words = ["sun", "star", "sun"]

print({w: len(w) for w in words})
# {'sun': 3, 'star': 4}

print(len({w for w in words}))
# 2

print(sum(n * n for n in range(1, 4)))
# 14
  • {key: value for ...} builds a Python dictionary.
  • {value for ...} builds a set, so repeated values go away.
  • (value for ...) builds a generator. It makes one value at a time.

There is no tuple comprehension. Round brackets give you a generator, so use tuple(...) around it if you need a tuple. The page on list vs tuple explains when a tuple is better.

Pro tip: If you only need a sum, a maximum or an any check, pass a generator, as in sum(n * n for n in data). It does not build the whole list in memory.

When not to use a list comprehension

A list comprehension is usually a little faster than a loop with append, because Python does less work for each item. Speed is rarely the reason to choose it. Clear code is.

Use a normal loop when:

  • you have more than two for parts or several conditions
  • you need try and except for bad values
  • you need break to stop early
  • you only want a side effect, such as printing
# Avoid: builds a useless list of None values
[print(n) for n in range(3)]

# Better
for n in range(3):
    print(n)

Compare it with map and filter too:

Task Comprehension Function form
Square each [n * n for n in a] list(map(lambda n: n * n, a))
Keep evens [n for n in a if n % 2 == 0] list(filter(lambda n: n % 2 == 0, a))
Text to int [int(x) for x in a] list(map(int, a))

When a ready function exists, like int, map is just as clear. Otherwise the comprehension is easier to read.

Practice questions with answers

Try each one before you look at the answer below.

  1. Get the cubes of 1 to 4.
  2. Keep words that start with "p" from ["pen", "book", "pin"].
  3. Replace negative numbers with 0 in [5, -2, 8, -1].
  4. Get all pairs (a, b) from 1 to 3 where a < b.
  5. Get the vowels in "education", in order.
print([n ** 3 for n in range(1, 5)])
# [1, 8, 27, 64]

print([w for w in ["pen", "book", "pin"] if w.startswith("p")])
# ['pen', 'pin']

print([n if n > 0 else 0 for n in [5, -2, 8, -1]])
# [5, 0, 8, 0]

print([(a, b) for a in range(1, 4) for b in range(1, 4) if a < b])
# [(1, 2), (1, 3), (2, 3)]

print([ch for ch in "education" if ch in "aeiou"])
# ['e', 'u', 'a', 'i', 'o']

For more tasks, use the Python practice problems and keep the Python cheat sheet open while you work. Once you can write these without help, prepare with Python interview questions. Learners who want guided projects can see the Python full stack course.

Frequently Asked Questions

What is a list comprehension in Python?
It is a short way to make a list from another sequence. It puts the value, the loop and an optional condition inside square brackets.
Can I use else in a list comprehension?
Yes, but place the whole if else before the for, as in ["Pass" if m >= 40 else "Fail" for m in marks]. An else after the final if is a syntax error.
Is a list comprehension faster than a for loop?
It is usually a little faster than a loop that calls append, but the gain depends on the work inside. Choose it mainly when it is easier to read.
How do nested for loops work in a list comprehension?
Write them in the same order as normal loops, with the outer loop first. [x for row in matrix for x in row] turns rows into one flat list.
Is there a tuple comprehension in Python?
No. Round brackets make a generator expression. Use tuple(x for x in data) when you need a tuple.

Want to Build Your Career in Data Science with AI?

Join CodeBegun and train with working industry engineers — See the Data Science course in Hyderabad

Apply for Demo Class →
Siva Prasad Galaba
Founder, CodeBegun · Staff Engineer

Founder of CodeBegun. 15+ years building Java systems at companies like Crunchyroll. Teaches Java, Spring Boot and system design the way the industry actually works, and mentors students through projects, mock interviews and placement preparation.

Technically reviewed by CodeBegun Technical TeamLast reviewed 3 December 2026 LinkedIn
Chat with us