Python List Comprehension
In this page:
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
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
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
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
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
letters = [c for c in "cat"]
print(letters)
Chapter Quiz — Complete all 12 topics to unlock
0/12 topics done
Complete these topics first: