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
- Every number goes into exactly one of the two lists, because of the
if/else. - The function returns two lists as a tuple, and
evens, odds = ...unpacks them into two variables. - The numbers keep their original order inside each list. 0 and -8 are even, because their remainder after dividing by 2 is 0. -3 is odd: in Python,
-3 % 2is 1. - An empty list gives two empty lists, with no error.
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]}