π
List Comprehension
Build lists in one line
Reward
+50 XP
Basic syntax
Create a new list by applying an expression to each item in an iterable.
squares = [x**2 for x in range(5)]
print(squares) # [0, 1, 4, 9, 16]With conditions
Add an if clause to filter items.
evens = [x for x in range(10) if x % 2 == 0]
print(evens) # [0, 2, 4, 6, 8]Try it yourself
Run the example below. Edit it and see what changes.
main.py
Output
Press Run to execute (Ctrl/Cmd+Enter)
Common mistakes
- β Making comprehensions too complex β keep them readable.
- β Confusing list comprehension [] with generator expression ().
