SyntaxStudy
Sign Up
Python Filtering with Comprehensions
Python Beginner 3 min read

Filtering with Comprehensions

Filtering with Comprehensions

Add an if clause at the end of a list comprehension to filter elements.

Example
evens = [x for x in range(20) if x % 2 == 0]
print(evens)
# [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
Pro Tip

The filter condition comes after the for clause, not before.