Python List Comprehension
In this page:
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
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
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
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
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
letters = [c for c in "cat"]
print(letters)
- Putting the condition in the wrong place, as in
[x for x in nums if x > 0 else 0], which is aSyntaxError; an if-else goes before thefor:[x if x > 0 else 0 for x in nums]. - Writing a comprehension so long or nested that it is unreadable, when a normal
forloop would be clearer. - Using a comprehension only for side effects, such as
[print(x) for x in items], which builds a useless list ofNonevalues.
Chapter Quiz — Complete all 12 topics to unlock
0/12 topics done
Complete these topics first: