PythonMastery
Python programs · Lists · beginner

Split a list into even and odd numbers in Python

Put the even numbers of a list into one list and the odd numbers into another, with one for loop, with two list comprehensions, or with a dictionary.

Go through the list once. If n % 2 is 0, the number is even and goes into one list. Otherwise it is odd and goes into the other list.

The program

python
def split_even_odd(numbers):
    evens = []
    odds = []
    for n in numbers:
        if n % 2 == 0:
            evens.append(n)
        else:
            odds.append(n)
    return evens, odds

numbers = [5, 10, 15, 22, 0, -3, -8, 41]
evens, odds = split_even_odd(numbers)

print("Even:", evens)
print("Odd: ", odds)
print(split_even_odd([]))
output
Even: [10, 22, 0, -8]
Odd:  [5, 15, -3, 41]
([], [])

How it works

Another way: two list comprehensions

python
numbers = [5, 10, 15, 22, 0, -3, -8, 41]

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

print(evens, odds)
output
[10, 22, 0, -8] [5, 15, -3, 41]

This is shorter, but it goes through the list twice, once for each comprehension. The loop above goes through it once. For short lists both are fine. The filter even numbers page explains the comprehension and filter() in more detail.

Using a dictionary

When there are more than two groups, a dictionary of lists is easier than many separate variables:

python
numbers = [5, 10, 15, 22, 0, -3, -8, 41]

groups = {"even": [], "odd": []}
for n in numbers:
    key = "even" if n % 2 == 0 else "odd"
    groups[key].append(n)

print(groups)
output
{'even': [10, 22, 0, -8], 'odd': [5, 15, -3, 41]}

Learn the idea: Lists & Sequences, Loops: for, while, and the Pythonic Patterns, Comprehensions: Lists, Dicts, Sets, Generators