← Back to Python Course | Chapter 6: Data Structures | Lesson 8 of 12

Python List Comprehension

A list comprehension is a shortcut to build a new list in one line, like a machine that takes in a row of items and pops out changed ones. It replaces a longer loop.
Syntax
python
new_list = [expression for item in iterable if condition]

Basic List Comprehension

List comprehensions build a new list from an existing iterable in one expression -- [x*2 for x in nums] -- and are generally both more concise and faster than the equivalent explicit for-loop-with-append pattern, since the looping happens in optimized C code.

Example: Basic List Comprehension

python
nums = [1, 2, 3]
doubled = [x * 2 for x in nums]  # builds a new list by doubling each item
print(doubled)

Filtering with Conditions

Appending an 'if condition' after the for clause filters which elements make it into the result -- [x for x in nums if x % 2 == 0] keeps only even numbers, skipping the rest entirely rather than transforming them.

Example: Filtering with Conditions

python
nums = [1, 2, 3, 4, 5, 6]
evens = [x for x in nums if x % 2 == 0]  # the if clause filters out odd numbers
print(evens)

Using If-Else Conditions

A ternary if-else placed before the for clause transforms every element based on a condition instead of filtering them out -- [even if x % 2 == 0 else odd for x in nums] keeps all items but changes their value.

Example: Using If-Else Conditions

python
nums = [1, 2, 3, 4]
labels = ["even" if x % 2 == 0 else "odd" for x in nums]  # if-else transforms every item
print(labels)

Nested Loops in Comprehension

You can chain multiple for clauses to flatten nested loops into one comprehension -- [x for row in matrix for x in row] visits every element of a 2D list in the same left-to-right order as writing the equivalent nested for loops.

Example: Nested Loops in Comprehension

python
matrix = [[1, 2], [3, 4]]
flat = [x for row in matrix for x in row]  # outer loop over rows, inner loop over each row's items
print(flat)

Iterating over Strings and Iterables

Because comprehensions work over any iterable, not just lists, you can build a list from a string's characters, a tuple's elements, or a generator's output using the exact same syntax.

Example: Iterating over Strings and Iterables

python
letters = [c for c in "cat"]
print(letters)
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Putting the condition in the wrong place, as in [x for x in nums if x > 0 else 0], which is a SyntaxError; an if-else goes before the for: [x if x > 0 else 0 for x in nums].
  2. Writing a comprehension so long or nested that it is unreadable, when a normal for loop would be clearer.
  3. Using a comprehension only for side effects, such as [print(x) for x in items], which builds a useless list of None values.

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.