ZetCode

Python list comprehensions

last modified November 17, 2026 Python 3.15

In this article we learn to use Python list comprehensions. We show how to transform, filter, and flatten lists, how to unpack tuples in the loop target, and how comprehensions differ from generator expressions.

Python list comprehension

A list comprehension is a syntactic construct which creates a list based on an existing iterable. List comprehensions provide a concise way to create lists. It is a common requirement to make new lists where each element is the result of some operations applied to each member of another sequence or iterable, or to create a subsequence of those elements that satisfy a certain condition.

Python list comprehension usage

A list comprehension can be used to:

The syntax of a list comprehension was influenced by mathematical notation of sets. The Python syntax was inspired by the Haskell programming language.

S = {x² : x in {0 ... 16}}

This is a mathematical notation for creating a set of integer values.

[expr for item in iterable]
[expr for item in iterable if cond]
[expr1 if cond else expr2 for item in iterable]

The first line is the basic form: the for clause takes one item from the iterable at a time and the expression is evaluated for it. The second line adds a filter; the expression is evaluated only for the items that satisfy the condition. The third line is a conditional expression in the expression part; it chooses between two values and produces one value for every item. A comprehension can also contain several for clauses and several if conditions.

From a for loop to a list comprehension

A list comprehension can be understood as a shorter form of a loop that builds a list. The following example creates the same list twice, first with an ordinary loop and then with a comprehension.

loop_to_comprehension.py
a = [1, 2, 3, 4]

squares = []
for n in a:
    squares.append(n * n)
print(squares)

squares = [n * n for n in a]
print(squares)

The loop starts with an empty list and appends one value in each iteration. The comprehension produces the same list in a single expression.

squares = [n * n for n in a]

There is no temporary variable, no append call, and no line that only creates the empty list. The construct was added in Python 2.0 by PEP 202 and has been part of the language since then.

$ python loop_to_comprehension.py
[1, 4, 9, 16]
[1, 4, 9, 16]

Python list comprehension transforming list

The following example transforms a list into another list with the help of the list comprehension.

multiply_elements.py
a = [1, 2, 3, 4, 5, 6]

b = [e * 2 for e in a]
print(b)

In the first example, we create a new list from an existing list by multiplying each element by 2.

b = [e * 2 for e in a]

Each of the elements of the a list is multiplied by 2 and the result is added to the new b list.

$ python multiply_elements.py
[2, 4, 6, 8, 10, 12]

Calculating Fahrenheit temperatures from Celsius

We have a list of temperatures in Celsius. We want to create a new list of temperatures expressed in Fahrenheit.

fahrenheit_celsius.py
celsius = [22, 28, 33, 42, 52]

fahr = [e * 9 / 5 + 32 for e in celsius]
print(fahr)

The example creates a new list of Fahrenheit temperatures calculated from a list of Celsius temperatures.

fahr = [e * 9 / 5 + 32 for e in celsius]

The calculation is done in the expression part of the list comprehension.

$ python fahrenheit_celsius.py
[71.6, 82.4, 91.4, 107.6, 125.6]

Python list comprehension filtering list

In the following example, we are going to filter a list with a list comprehension.

filter_positive.py
a = [-4, 2, 0, -1, 12, -3]

b = [e for e in a if e > 0]
print(b)

We have a list of integers. We create a new list where we only include positive integers.

b = [e for e in a if e > 0]

To include only positive numbers, we use an if condition, which is applied on each of the elements; the elements are included in the new list only if they satisfy the condition.

$ python filter_positive.py
[2, 12]

Python list comprehension filtering by type

The next example filters elements by their type.

filter_by_type.py
a = ['a', 2, 'c', 12, 3, 'd']

b = [e for e in a if isinstance(e, int)]
c = [e for e in a if isinstance(e, str)]

print(b)
print(c)

We have a list of elements, which are integers and strings. We create two new lists; one having only integers and one only strings.

b = [e for e in a if isinstance(e, int)]

Here we create a list b, which will contain only integer values. The isinstance function checks whether the element is an instance of the given type.

$ python filter_by_type.py
[2, 12, 3]
['a', 'c', 'd']

Python list comprehension predicate

A predicate is a function that returns a boolean value. If the condition is too complex, we can put it into a predicate.

predicate.py
def is_vowel(c):
    return c.lower() in 'aeiou'


sentence = 'There are eagles in the sky.'

vowels = [c for c in sentence if is_vowel(c)]
print(vowels)

The example picks out all vowels from a sentence.

def is_vowel(c):
    return c.lower() in 'aeiou'

The function is a predicate. It returns True for a vowel character, regardless of its case.

vowels = [c for c in sentence if is_vowel(c)]

The logic of the if condition is delegated to the is_vowel predicate.

$ python predicate.py
['e', 'e', 'a', 'e', 'e', 'a', 'e', 'i', 'e']

The if condition in front

A conditional expression can be placed in the expression part as well. This way the data can be transformed.

even_odd.py
data = ['even' if i % 2 == 0 else 'odd' for i in range(7)]
print(data)

In the example, we transform the values into 'even' and 'odd' values using the list comprehension. Unlike the if clause at the end, a conditional expression in front does not filter any elements; it needs the else part and produces one value for each element.

$ python even_odd.py
['even', 'odd', 'even', 'odd', 'even', 'odd', 'even']

Python list comprehension unpacking in the loop target

The target of the for clause does not have to be a single name. When the iterable yields tuples, the target can unpack them into several variables.

unpacking_target.py
people = [('Alice', 30), ('Bob', 17), ('Carol', 25)]

adults = [name for name, age in people if age >= 18]
print(adults)

names = ['sky', 'forest']
lengths = [3, 6]

pairs = [f'{n}: {l}' for n, l in zip(names, lengths)]
print(pairs)

words = ['sky', 'cup', 'forest']
numbered = [f'{i} {w}' for i, w in enumerate(words)]
print(numbered)

The first comprehension goes through a list of pairs. Each pair is split into name and age, and the condition tests only the age.

adults = [name for name, age in people if age >= 18]

The other two examples use the same idea with built-in functions. zip pairs the elements of two sequences, and enumerate produces an index together with each element.

$ python unpacking_target.py
['Alice', 'Carol']
['sky: 3', 'forest: 6']
['0 sky', '1 cup', '2 forest']

Python list comprehensions and dictionaries

A comprehension over a dictionary iterates over its keys, so items() is needed when the values are required as well.

comprehension_dict.py
data = {'sky': 3, 'cup': 5, 'forest': 6}

keys = [k for k in data]
print(keys)

items = [f'{k}={v}' for k, v in data.items()]
print(items)

long_words = [k for k, v in data.items() if v > 3]
print(long_words)

The first comprehension reads only the keys. The second one unpacks the pairs returned by items() and formats them.

items = [f'{k}={v}' for k, v in data.items()]

The last example filters the items by value. Dictionaries keep insertion order, so the resulting list follows the order in which the keys were added. See Python dictionary for more about dictionaries.

$ python comprehension_dict.py
['sky', 'cup', 'forest']
['sky=3', 'cup=5', 'forest=6']
['cup', 'forest']

Python list comprehensions and text

Comprehensions are often used to clean and split text. The next example processes a comma-separated line.

comprehension_text.py
line = ' sky , forest , cup '
words = [w.strip() for w in line.split(',')]
print(words)

titled = [w.capitalize() for w in words]
print(titled)

consonants = [c for c in 'hello' if c not in 'aeiou']
print(consonants)
print(''.join(consonants))

The first comprehension splits the line and removes the surrounding spaces from every item. The second one applies a method to each word.

words = [w.strip() for w in line.split(',')]

The last example iterates over the characters of a string. The filtered characters can be joined back into a string with join, a common idiom when text is cleaned character by character.

$ python comprehension_text.py
['sky', 'forest', 'cup']
['Sky', 'Forest', 'Cup']
['h', 'l', 'l']
hll

Python list comprehension multiple if conditions

It is possible to use multiple if conditions in Python list comprehensions.

multiple_conditions.py
a = [9, 2, 18, 14, 22, 11, 7, 19, 23]

b = [e for e in a if e > 10 if e < 20]
print(b)

c = [e for e in a if 10 < e < 20]
print(c)

We create a new list of integers from list a, which are greater than 10 and lower than 20.

b = [e for e in a if e > 10 if e < 20]

In this list comprehension, we use two if conditions. An element is included only if it satisfies both of them.

c = [e for e in a if 10 < e < 20]

The same filter can be written with a single chained comparison.

$ python multiple_conditions.py
[18, 14, 11, 19]
[18, 14, 11, 19]

Python list comprehension multiple for loops

It is possible to have multiple for loops in a Python list comprehension.

multiple_for_loops.py
a = [1, 2, 3]
b = ['A', 'B', 'C']

c = [str(i) + j for i in a for j in b]
print(c)

d = [str(i) + j for j in b for i in a]
print(d)

The first comprehension creates a Cartesian product of two lists.

c = [str(i) + j for i in a for j in b]

The second loop is nested in the first one, so it runs completely for each element of the first list.

d = [str(i) + j for j in b for i in a]

The order of the clauses matters. Swapping them changes which loop is the outer one, so the pairs are generated in a different order.

$ python multiple_for_loops.py
['1A', '1B', '1C', '2A', '2B', '2C', '3A', '3B', '3C']
['1A', '2A', '3A', '1B', '2B', '3B', '1C', '2C', '3C']

Python list comprehension flattening a list

The next example shows how to flatten a Python list.

flatten_list.py
nums = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

c = [e for num in nums for e in num]
print(c)

The nums list is a list of nested lists. We flatten the list with a list comprehension.

c = [e for num in nums for e in num]

The first loop goes through the outer list; the second for loop goes through the nested lists. The loops are written in the same order as they would be in nested for statements.

$ python flatten_list.py
[1, 2, 3, 4, 5, 6, 7, 8, 9]

Unpacking in list comprehensions

Since Python 3.15, the expression part of a comprehension can use the * unpacking operator. The elements of each iterable are added to the new list one by one. This is a shorter way to flatten nested lists.

unpacking.py
nums = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

c = [*num for num in nums]
print(c)

d = [*num[1:] for num in nums if sum(num) > 6]
print(d)

The example flattens the same nested list with unpacking.

c = [*num for num in nums]

For each nested list, *num unpacks its elements into the result. It replaces the second for clause of the previous example.

d = [*num[1:] for num in nums if sum(num) > 6]

Conditions and transformations work as usual. Here we drop the first nested list, whose sum is 6, and the first element of the remaining lists. The syntax causes a SyntaxError in Python 3.14 and older. Set and dictionary comprehensions, ** unpacking, and generator expressions are covered in Python unpacking in comprehensions.

$ python unpacking.py
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[5, 6, 8, 9]

The walrus operator in list comprehensions

The assignment expression :=, also called the walrus operator, stores a value computed in the condition so that the expression part can use it.

walrus.py
words = ['sky', 'forest', 'cup', 'Universe', 'war', 'summer']

lengths = [(w, n) for w in words if (n := len(w)) > 3]
print(lengths)
print(n)

We keep the words longer than three characters together with their lengths.

lengths = [(w, n) for w in words if (n := len(w)) > 3]

The length of each word is computed only once, in the condition, and the result is reused in the tuple.

print(n)

A walrus target is the exception to the rule that comprehension variables are local: n is bound in the enclosing scope and remains available after the comprehension. See Python walrus operator for more.

$ python walrus.py
[('forest', 6), ('Universe', 8), ('summer', 6)]
6

Comprehension variables are local

A list comprehension has its own scope. The loop variable is local to the comprehension, so it does not overwrite a name with the same spelling in the enclosing scope.

comprehension_scope.py
x = 'outer'

squares = [x * x for x in range(4)]
print(squares)
print(x)

The comprehension uses x as its loop variable, but the x defined before it keeps its value.

x = 'outer'
squares = [x * x for x in range(4)]

This behaviour differs from Python 2, where the loop variable leaked into the surrounding scope, and from a plain for loop, which rebinds the name. The walrus operator is the only way for a comprehension to leave a value behind. See Python variable shadowing for related examples.

$ python comprehension_scope.py
[0, 1, 4, 9]
outer

Python nested list comprehensions

The initial expression in a Python list comprehension can be another list comprehension.

nested_list_comprehension.py
m1 = [[1, 2, 3],
      [4, 5, 6],
      [7, 8, 9]]

m1_tr = [[row[i] for row in m1] for i in range(3)]
print(m1_tr)

The example defines a matrix and a list comprehension creates a transposed matrix from the original matrix.

m1_tr = [[row[i] for row in m1] for i in range(3)]

The outer comprehension runs once for each column index, and the inner one builds a row of the new matrix from the i-th element of every original row.

$ python nested_list_comprehension.py
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]

Set, dictionary comprehensions, and generator expressions

List comprehensions have three siblings. Dictionary and set comprehensions use curly braces, and a generator expression uses parentheses. All four forms share the same for and if clauses.

siblings.py
data = {'sky': 3, 'cup': 5}

doubled = {k: v * 2 for k, v in data.items()}
print(doubled)

remainders = {n % 3 for n in range(10)}
print(remainders)

squares = (n * n for n in range(5))
print(type(squares).__name__)
print(list(squares))

The first comprehension builds a dictionary, which is recognised by the colon between the key and the value expression.

doubled = {k: v * 2 for k, v in data.items()}

The second one builds a set, so duplicate values disappear. The last form does not build a collection at all.

squares = (n * n for n in range(5))

The brackets decide what is created. Square brackets make a list, curly braces with a colon make a dictionary, curly braces without one make a set, and parentheses make a generator expression. See Python generators for the generator form.

$ python siblings.py
{'sky': 6, 'cup': 10}
{0, 1, 2}
generator
[0, 1, 4, 9, 16]

Generator expressions

A generator expression produces values on demand instead of building a list. This makes it suitable for data that does not fit in memory, including sequences that never end.

lazy_generator.py
def natural_numbers():
    n = 1
    while True:
        yield n
        n += 1


squares = (n * n for n in natural_numbers())
print([next(squares) for _ in range(6)])

The generator function yields natural numbers forever, yet the program finishes, because only the requested values are computed.

squares = (n * n for n in natural_numbers())

The generator remembers its position between calls, so each next continues where the previous one stopped. The underscore is the usual name for a loop variable whose value is not used. A list comprehension over the same generator would never finish.

$ python lazy_generator.py
[1, 4, 9, 16, 25, 36]

Python list comprehension performance

A list comprehension is usually faster than a loop that calls append, because the list is built by the interpreter without a method call in each iteration. The timeit module measures the difference between the three common ways to build a list.

Each command below runs the statement many times and reports the average duration of one run. The exact numbers depend on the machine and on the Python build, so only the ratio between them is meaningful.

The comprehension is about a quarter faster than the explicit loop, and map with a lambda is the slowest of the three, because calling the lambda costs more than evaluating the expression. Since Python 3.12, comprehensions are inlined into the surrounding code (PEP 709), which removed a hidden function call and made them faster still.

Speed should not be the only reason to choose a comprehension. When the result is consumed once, a generator expression avoids the list entirely, and when the comprehension needs more than two for clauses or a long condition, an ordinary loop is easier to read and debug.

$ python -m timeit -s 'a = range(1000)' '[e * 2 for e in a]'
20000 loops, best of 5: 15 usec per loop
$ python -m timeit -s 'a = range(1000)' 'b = []' 'for e in a: b.append(e * 2)'
10000 loops, best of 5: 19.9 usec per loop
$ python -m timeit -s 'a = range(1000)' 'list(map(lambda e: e * 2, a))'
10000 loops, best of 5: 29.5 usec per loop

Common mistakes

The most common mistake is to use a comprehension for its side effects instead of its result.

comprehension_mistakes.py
words = ['sky', 'forest', 'cup']

result = [print(w) for w in words]
print(result)

data = [e if e % 2 == 0 else -1 for e in range(10)]
print(data)

The first comprehension prints every word, but it also collects the return values of print, which are all None. The list serves no purpose and only wastes memory.

The second mistake concerns the position of else. The following line puts it into the filter and does not run.

[e for e in range(10) if e % 2 == 0 else -1]

Python reports SyntaxError: invalid syntax. An else is allowed only in the conditional expression, so it must come before the for clause.

[e if e % 2 == 0 else -1 for e in range(10)]

The correct form is used in the listing above and produces one value for every number. Two more habits are worth avoiding: building a list only to copy it, where a.copy() is clearer, and nesting three or more for clauses.

$ python comprehension_mistakes.py
sky
forest
cup
[None, None, None]
[0, -1, 2, -1, 4, -1, 6, -1, 8, -1]

Sieve of Eratosthenes

Sieve of Eratosthenes is an ancient algorithm to compute prime numbers. A prime number (or a prime) is a natural number greater than 1 that has no positive divisors other than 1 and itself. The algorithm iteratively marks as composite (i.e., not prime) the multiples of each prime, starting with the multiples of 2.

sieve_of_eratosthenes.py
import math

no_primes = {j for i in range(2, math.isqrt(100) + 1)
             for j in range(i * 2, 100, i)}
primes = [e for e in range(2, 100) if e not in no_primes]
print(primes)

The example computes prime numbers up to 100.

no_primes = {j for i in range(2, math.isqrt(100) + 1)
             for j in range(i * 2, 100, i)}

First, we create a set of numbers that are not primes. It is enough to mark the multiples of numbers up to the square root of 100, and math.isqrt returns that root as an integer. We use a set comprehension, because checking membership in a set is much faster than in a list.

primes = [e for e in range(2, 100) if e not in no_primes]

Prime numbers are simply the numbers that are not included in the no_primes set.

$ python sieve_of_eratosthenes.py
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]

Source

Python data structures - Python tutorial

Displays for lists, sets and dictionaries - Python reference

PEP 202 - List Comprehensions

PEP 709 - Inlined comprehensions

In this article we have presented Python list comprehensions. We have covered transforming and filtering lists, unpacking tuples in the loop target, dictionary and text processing, the scope of comprehension variables, and the difference between list comprehensions and generator expressions. For related topics, see Python list loop, Python filter list, Python lambda, and Python generators.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Python tutorials.