Skip to main content

How to Build a List with a List Comprehension in Python

· 3 min read
Jagdish Kumawat
Founder @ Dewiride

To make a new list from an existing one, such as every number squared or only the even ones, Python has a short form called a list comprehension. It fits the loop and the new list into one line. This guide builds two lists from five numbers, with real output from Python 3.15.2.

Syntax​

Syntax
<new list> = [<expression> for <item> in <list>]
<new list> = [<expression> for <item> in <list> if <condition>]
PartWhat it means
<expression>What each item of the new list is, usually built from <item>
for <item> in <list>Goes through the items one by one
if <condition>Optional. Only items for which it's true go into the new list

The Python tutorial: "A list comprehension consists of brackets containing an expression followed by a for clause, then zero or more for or if clauses."

Prerequisites​

  • uv and Python 3. This guide uses uv 0.13.10 with Python 3.15.2, in a project made with uv init.

Step 1: Write the Script​

squares.py
numbers = [1, 2, 3, 4, 5]

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

even_numbers = [n for n in numbers if n % 2 == 0]
print(even_numbers)

The squares.py script in a macOS-style code window: numbers 1 to 5, squares = [n * n for n in numbers], and even_numbers = [n for n in numbers if n % 2 == 0], each printed.

  • [n * n for n in numbers]: each n becomes n * n.
  • if n % 2 == 0: keeps the numbers that leave no remainder when divided by 2.

Step 2: Run It​

Terminal
uv run python squares.py
Output
[1, 4, 9, 16, 25]
[2, 4]

The script's output in a terminal: [1, 4, 9, 16, 25] and [2, 4].

The first list has one square per number; the second has only the even numbers.

Common Mistakes​

MistakeWhat happensDo this instead
Round brackets instead of square ones(n * n for n in numbers) printed <generator object <genexpr> at 0x...>, not a listSquare brackets, or list(...) around it: list(n * n for n in numbers) gave [1, 4, 9]
Using the loop name after the comprehensionprint(n) raised NameError: name 'n' is not defined: n exists only inside the bracketsKeep the work inside the comprehension, or use a for loop

Troubleshooting​

SymptomLikely causeFix
The new list is emptyThe if condition is never truePrint a few values of the condition, such as n % 2

FAQ​

Is a comprehension faster than a for loop?​

It does the same work with less code; choose it when the line stays easy to read. A long or nested one is often clearer as a loop.

Does it change the original list?​

No. numbers is still [1, 2, 3, 4, 5]; the comprehension makes a new list.

Conclusion​

[n * n for n in numbers] built [1, 4, 9, 16, 25], and adding if n % 2 == 0 kept [2, 4], each in one line.

Additional Resources​