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
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)
Even: [12, 18, 0, -4] Odd: [7, 3, 25, 9]
How it works
[n for n in numbers if n % 2 == 0]is a list comprehension with a condition. It goes throughnumbersand keeps eachnfor which the condition is true.- 0 and -4 are even too:
0 % 2and-4 % 2are both 0. - The original list does not change.
The same thing as a for loop:
numbers = [12, 7, 3, 18, 0, -4, 25, 9] evens = [] for n in numbers: if n % 2 == 0: evens.append(n) print(evens)
[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:
numbers = [12, 7, 3, 18, 0, -4, 25, 9] evens = list(filter(lambda n: n % 2 == 0, numbers)) print(evens)
[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.