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

Python List Comprehension

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]
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]
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]
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]
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)

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.