List and Dict Comprehensions in Python
List comprehensions
List comprehensions let you build a new list from an existing one in a single expression.
Basics
Filter values from another list:
[x for x in [1,2,3,4] if x % 2 == 0]
This returns [2, 4]
. Without the if
, it simply copies the list.
Variations
Transform the elements:
[x/2 for x in [1,2,3,4]]
Repeat the same element to expand a list:
['a' for _ in range(100)]
Pull the first item out of nested lists:
[x[0] for x in [[1,2], [3,4], [5,6]]]
Nested loops:
[n for row in [[1,2], [3,4], [5,6]] for n in row]
Generate tuples:
[(x, x + 10) for x in [1,2]]
Multiple variables:
[(x,y) for x,y in {1:2, 4:5}.items() if x % 2 == 0]
Combined with conditional expressions:
[x if x % 3 == 0 else 1 for x in range(10)]
[(x,y) if x % 2 == 0 else (y, 3) for x,y in {1:2, 4:5}.items()]
Dict comprehensions
Dictionaries support a similar syntax:
{x:y for y,x in {'1':'2', '3':'4'}.items() if '1' in y}
References:
《A Visual Intro to Python List Comprehensions》
《Dict comprehensions》