PythonMastery
Python programs · Lists · beginner

Filter even numbers from a list in Python

Make a new list with only the even numbers from a list in Python, using a list comprehension, a for loop, or filter() with a lambda.

A number is even when n % 2 is 0. To keep only the even numbers, test each number and collect the ones that pass.

The program

python
numbers = [12, 7, 3, 18, 0, -4, 25, 9]

evens = [n for n in numbers if n % 2 == 0]
odds = [n for n in numbers if n % 2 != 0]

print("Even:", evens)
print("Odd: ", odds)
output
Even: [12, 18, 0, -4]
Odd:  [7, 3, 25, 9]

How it works

The same thing as a for loop:

python
numbers = [12, 7, 3, 18, 0, -4, 25, 9]

evens = []
for n in numbers:
    if n % 2 == 0:
        evens.append(n)

print(evens)
output
[12, 18, 0, -4]

Another way: filter()

filter() takes a function and a list, and keeps the items for which the function returns True. A lambda is a short function without a name:

python
numbers = [12, 7, 3, 18, 0, -4, 25, 9]

evens = list(filter(lambda n: n % 2 == 0, numbers))
print(evens)
output
[12, 18, 0, -4]

filter() gives an iterator, so list(...) is needed to see the result as a list. Most Python programmers find the list comprehension easier to read.

Related programs: List comprehension with if condition, Split a list into even and odd numbers.

Learn the idea: Comprehensions: Lists, Dicts, Sets, Generators, Lambda & Functional Programming, Lists & Sequences