Skip to content
PythonComprehensions and Functional Patternsbeginner25 min read

List Comprehensions

Build lists concisely with expressions, loops, filters, and conditional logic while keeping Python code readable.

In this lesson, you will learn

  • ✓Explain what a list comprehension does and identify its components.
  • ✓Convert a simple for loop that builds a list into an equivalent list comprehension.
  • ✓Use conditions to filter which items are included in a list.
  • ✓Use conditional expressions to choose the value produced for each item.
  • ✓Trace nested comprehensions and predict their output.
  • ✓Recognize empty-iterable behavior and choose a comprehension or ordinary loop based on readability.

1. What is a list comprehension?

A list comprehension creates a new list by evaluating an expression for items obtained from an iterable. Its basic syntax is [expression for item in iterable].

The expression determines what value is placed into the new list. The for clause supplies each item in turn, and the iterable provides the items to process. Python evaluates the expression for each item and collects the resulting values in order.

A list comprehension does not change the original iterable just because it creates a new list. Whether the original data changes depends on what the expression itself does. For beginner exercises, expressions that calculate or transform values are usually easiest to understand.

Create a list of squares

Create a list of squares
python
squares = [n * n for n in range(1, 5)]
print(squares)
Output
[1, 4, 9, 16]

The expression is n * n. The for clause assigns each value from range(1, 5) to n. range(1, 5) produces 1, 2, 3, and 4; the endpoint 5 is excluded. The expression produces 1, 4, 9, and 16, in that order. The resulting list is stored in squares and then printed.

Note

Remember the basic pattern: [expression for item in iterable]. The expression comes first in the written syntax, even though Python obtains each item before evaluating the expression for that item.

2. Transform each item

A common use of list comprehensions is to transform every item in an existing collection. The output list contains one result for each item produced by the iterable, unless a filter excludes some items.

The transformation can perform arithmetic, call a string method, or use another expression. The result list preserves the iteration order of the source iterable.

The item name is a variable used by the comprehension. Choose a name that makes the transformation understandable, such as number, word, or price.

Double every number

Double every number
python
numbers = [1, 2, 3, 4]
doubles = [number * 2 for number in numbers]
print(doubles)
Output
[2, 4, 6, 8]

Python takes each number from the original list. It multiplies the number by 2. The results are collected in a new list. The original numbers list remains [1, 2, 3, 4].

Note

A transformation comprehension usually creates one output item per input item. If you also add a filtering condition, some input items may be omitted.

3. Filter items with if

A filtering comprehension includes an item only when a condition is true. Its syntax is [expression for item in iterable if condition].

Python checks the condition for each item. If the condition is true, Python evaluates the expression and includes the result. If the condition is false, that item contributes nothing to the result list.

The if clause in this form filters items; it does not select between two output values. To choose between two values for every item, use a conditional expression, which is covered in the next section.

Keep only even numbers

Keep only even numbers
python
numbers = [1, 2, 3, 4, 5, 6]
evens = [number for number in numbers if number % 2 == 0]
print(evens)
Output
[2, 4, 6]

The expression number % 2 calculates the remainder after division by 2. An even integer has a remainder of 0 when divided by 2. Only 2, 4, and 6 satisfy the condition. The other values are skipped, so they do not appear in evens.

Note

The filtering condition goes after the for clause. Do not confuse [x for x in values if condition], which filters items, with [x if condition else y for x in values], which chooses an output value for each item.

4. Use conditional expressions

Sometimes you want to include every item but produce a different output value depending on a condition. Python supports this using a conditional expression inside the comprehension.

The syntax is [value_if_true if condition else value_if_false for item in iterable]. For each item, Python checks the condition and places one of the two values into the result list.

Unlike a filtering if clause, a conditional expression normally produces one output item for every input item. The words if and else belong to the expression before the for clause.

Label numbers as even or odd

Label numbers as even or odd
python
numbers = [1, 2, 3, 4, 5]
labels = ['even' if number % 2 == 0 else 'odd' for number in numbers]
print(labels)
Output
['odd', 'even', 'odd', 'even', 'odd']

For each number, Python checks whether its remainder when divided by 2 is zero. If the condition is true, the expression produces 'even'. Otherwise, it produces 'odd'. Every input number contributes one label to the result list.

Note

Use a filtering if when you want to remove items. Use if/else inside the expression when you want every item to contribute a value.

5. Work with strings, ranges, and empty iterables

A list comprehension can iterate over many kinds of iterables, not just lists. For example, it can process characters in a string or numbers generated by range().

An iterable does not need to contain any items. If the iterable is empty, the comprehension produces an empty list because there are no items for which to evaluate the expression.

The range() function excludes its stop value. Therefore, range(1, 5) produces 1 through 4, while range(5) produces 0 through 4. Understanding the iterable is essential to predicting the output of a comprehension.

Select vowels from a string

Select vowels from a string
python
word = 'comprehension'
vowels = [letter for letter in word if letter in 'aeiou']
print(vowels)
Output
['o', 'e', 'e', 'i', 'o']

Python iterates over the characters of the string from left to right. The condition letter in 'aeiou' checks whether each character is a lowercase vowel. Only matching characters are included. Repeated vowels remain repeated because the comprehension processes each occurrence separately.

Caution

An empty iterable normally produces an empty list without an exception. If your program requires at least one item, check that requirement explicitly rather than assuming the comprehension will produce a value.

6. Nested list comprehensions

A nested list comprehension contains more than one for clause. It can be useful when working with pairs of values, grids, or nested collections.

In [expression for first in first_iterable for second in second_iterable], the first for clause is the outer iteration and the second is the inner iteration. For each outer item, Python processes all items from the inner iterable.

Nested comprehensions can become difficult to read when they contain many loops or conditions. Use an ordinary loop when the logic becomes hard to explain or debug.

Create coordinate pairs

Create coordinate pairs
python
pairs = [(x, y) for x in [1, 2] for y in [10, 20]]
print(pairs)
Output
[(1, 10), (1, 20), (2, 10), (2, 20)]

The outer loop assigns x = 1 first. For x = 1, the inner loop produces (1, 10) and (1, 20). Then the outer loop assigns x = 2. The inner loop produces (2, 10) and (2, 20). The result contains four tuples in the same order as the nested loops.

Note

Read nested comprehensions in the same order as equivalent nested for loops: process the outer item, then run the inner iteration for that item.

7. Readability and common design choices

List comprehensions are most useful when the transformation or filtering rule is short and easy to understand. A single expression with one loop is often clear and concise.

An ordinary for loop may be preferable when the operation needs several statements, complicated branching, exception handling, logging, or multiple side effects. A comprehension is intended to build a list, not to replace every loop in a program.

A comprehension creates a new list, which consumes memory for its resulting items. For very large data sets, consider whether processing items one at a time with a generator expression or a loop would be more suitable. Generator expressions are a separate topic and do not immediately create a list.

The variable used by a comprehension in Python 3 does not leak into the surrounding scope as a loop variable would in a normal for statement. Avoid relying on a comprehension's iteration variable after the comprehension.

A readable one-line transformation

A readable one-line transformation
python
prices = [10, 20, 30]
with_tax = [price * 1.1 for price in prices]
print(with_tax)
Output
[11.0, 22.0, 33.0]

The expression multiplies every price by 1.1. Python calculates each result as a floating-point value. The result list contains one value per price. This short transformation is a suitable use for a list comprehension.

Note

Prefer readable code over the shortest possible code. A comprehension should make the transformation easier to understand, not harder.

Common pitfalls to avoid

Real debugging lessons and exact syntax contrasts to avoid runtime bugs

#1 Putting the expression and for clause in the wrong order.

Why it happens: A list comprehension places its output expression before the for clause, followed by optional filters.

Incorrect Approach
script.py
python
Putting the expression and for clause in the wrong order.
Correct Solution
script.py
python
Use [expression for item in iterable]. The expression comes first in the syntax.

Key takeaway: Use [expression for item in iterable]. The expression comes first in the syntax.

#2 Confusing filtering with a conditional expression.

Why it happens: A filter decides whether an input item is included; a conditional expression chooses a replacement value for each included item.

Incorrect Approach
script.py
python
Confusing filtering with a conditional expression.
Correct Solution
script.py
python
Use [expression for item in iterable if condition] to omit items. Use [value_if_true if condition else value_if_false for item in iterable] to choose a value for every item.

Key takeaway: Use [expression for item in iterable if condition] to omit items. Use [value_if_true if condition else value_if_false for item in iterable] to choose a value for every item.

#3 Forgetting that range() excludes its stop value.

Why it happens: range(start, stop) excludes stop, so include the endpoint by adjusting the stop value or choosing a different iteration strategy.

Incorrect Approach
script.py
python
Forgetting that range() excludes its stop value.
Correct Solution
script.py
python
range(1, 5) produces 1, 2, 3, and 4, not 5.

Key takeaway: range(1, 5) produces 1, 2, 3, and 4, not 5.

#4 Expecting an empty iterable to produce a value.

Why it happens: An empty iterable produces an empty comprehension result because there are no elements to transform.

Incorrect Approach
script.py
python
Expecting an empty iterable to produce a value.
Correct Solution
script.py
python
An empty iterable produces an empty list because no item is available to process.

Key takeaway: An empty iterable produces an empty list because no item is available to process.

#5 Assuming a comprehension modifies the original list.

Why it happens: A comprehension builds a new list rather than modifying the original iterable in place.

Incorrect Approach
script.py
python
Assuming a comprehension modifies the original list.
Correct Solution
script.py
python
A comprehension normally creates a new list. The original remains unchanged unless the expression itself performs a mutation.

Key takeaway: A comprehension normally creates a new list. The original remains unchanged unless the expression itself performs a mutation.

#6 Writing a very complicated comprehension to save lines.

Why it happens: Saving lines is not always worth reduced readability; use a normal loop when the logic becomes difficult to scan or debug.

Incorrect Approach
script.py
python
Writing a very complicated comprehension to save lines.
Correct Solution
script.py
python
Use a normal loop when multiple operations, complex branching, or side effects make the logic difficult to read.

Key takeaway: Use a normal loop when multiple operations, complex branching, or side effects make the logic difficult to read.

#7 Assuming a comprehension always returns a list of the same length as the input.

Why it happens: A comprehension with a filter may return fewer elements than the input, and a nested comprehension can change the result size substantially.

Incorrect Approach
script.py
python
Assuming a comprehension always returns a list of the same length as the input.
Correct Solution
script.py
python
A transformation without filtering generally produces one result per input item. A filtering clause can produce fewer items.

Key takeaway: A transformation without filtering generally produces one result per input item. A filtering clause can produce fewer items.

Ready for hands-on challenges?

Test your skills with shuffled coding challenges in the Practice Arena.

Practice Arena →

Technical and placement interview questions

Frequently tested interview questions with detailed, full answers (click to expand)

Q1:What is a list comprehension in Python?
Answer:
A list comprehension is a concise way to create a new list by evaluating an expression for each item in an iterable. Its basic syntax is [expression for item in iterable]. An optional filtering condition can control which items are included.
Q2:How does a list comprehension differ from a normal for loop?
Answer:
Both can build the same list. A comprehension expresses the transformation in one expression, while a for loop creates or updates the list through statements such as append(). Comprehensions are often concise for simple transformations; loops can be clearer for complex logic or multiple side effects.
Q3:How do you filter values with a list comprehension?
Answer:
Place a condition after the for clause, as in [n for n in numbers if n > 5]. Only items satisfying the condition contribute a result to the new list.
Q4:What is the difference between a filtering if and an if/else conditional expression?
Answer:
A filtering if, written after the for clause, omits items that fail the condition. A conditional expression, written before the for clause as value_if_true if condition else value_if_false, selects an output value for each item.
Q5:What happens when a list comprehension iterates over an empty iterable?
Answer:
It produces an empty list because there are no items for which to evaluate the expression. For example, [n * 2 for n in []] returns [].
Q6:How do nested list comprehensions work?
Answer:
Each for clause represents another iteration. In [number for row in matrix for number in row], Python selects a row first and then processes each number in that row. The result contains the numbers in iteration order.
Q7:When should you avoid a list comprehension?
Answer:
Avoid it when the expression becomes difficult to understand, the logic needs multiple statements, or the code relies on complicated branching and side effects. A normal for loop may be easier to maintain and debug.

Key takeaways

  • The basic list comprehension syntax is [expression for item in iterable].
  • A transformation expression determines the value placed in the new list.
  • A filtering if clause includes only items that satisfy its condition.
  • An if/else conditional expression chooses an output value for every item.
  • The order of iteration is preserved, and an empty iterable produces an empty list.
  • Nested comprehensions can process nested collections or create combinations of values.
  • A list comprehension creates a new list; it does not automatically modify the source collection.
  • Prefer readable comprehensions for simple transformations and ordinary loops for complex logic.
Was this lesson helpful?
Found an error? Report an issue

Related Topics & Next Steps

4 Recommended Lessons

Strengthen your Python foundation with these complementary core lessons: