2. Filtering a list

Use a comprehension to filter values instead of building the list with a loop.

Comprehensions keep the element transformation and filter condition together in one expression, which makes the resulting list easy to understand at a glance. They also avoid the visual overhead of a temporary list plus repeated append calls.

2.1. Don’t do this

1nums = []
2for i in range(100):
3    if i % 2 == 0:
4        nums.append(i)

2.2. Do this

1nums = [i for i in range(100) if i % 2 == 0]