Editor

Python Program to Separate Even and Odd Numbers in a List

Beginner · Lists

An even number divides by 2 with no remainder, like 12 or 30, and an odd number leaves a remainder of 1, like 7 or 25. This program goes through a list and puts each number into an even list or an odd list.

Program

even_and_odd_in_list.py
numbers = [12, 7, 25, 30, 41, 18, 9, 64] # or: numbers = [int(x) for x in input("Enter numbers: ").split()]
even_numbers = []
odd_numbers = []
for num in numbers:
if num % 2 == 0: # no remainder when divided by 2
even_numbers.append(num)
else:
odd_numbers.append(num)
print("List:", numbers)
print(f"Even numbers ({len(even_numbers)}):", even_numbers)
print(f"Odd numbers ({len(odd_numbers)}):", odd_numbers)
Output
List: [12, 7, 25, 30, 41, 18, 9, 64]
Even numbers (4): [12, 30, 18, 64]
Odd numbers (4): [7, 25, 41, 9]

How it works

  1. num % 2 is the remainder when num is divided by 2: 0 for even numbers and 1 for odd ones.
  2. Each number is appended to even_numbers or odd_numbers depending on that remainder.
  3. The numbers keep the order they had in the original list.
  4. len() of each list gives how many even and odd numbers there are.

Other ways to write it

Using list comprehensions

Using list comprehensions
numbers = [12, 7, 25, 30, 41, 18, 9, 64]
even_numbers = [n for n in numbers if n % 2 == 0]
odd_numbers = [n for n in numbers if n % 2 != 0]
print("Even numbers:", even_numbers)
print("Odd numbers:", odd_numbers)
Output
Even numbers: [12, 30, 18, 64]
Odd numbers: [7, 25, 41, 9]

Each comprehension keeps only the numbers that pass its condition. It is shorter, but the list is scanned twice.

Sum of even and odd numbers

Sum of even and odd numbers
numbers = [12, 7, 25, 30, 41, 18, 9, 64]
even_sum = 0
odd_sum = 0
for num in numbers:
if num % 2 == 0:
even_sum += num
else:
odd_sum += num
print("Sum of even numbers:", even_sum)
print("Sum of odd numbers:", odd_sum)
Output
Sum of even numbers: 124
Sum of odd numbers: 82

The same test can add the numbers up instead of collecting them, which is another common school exercise.

Try it yourself

Add negative numbers such as -4 and -7 to the list and check that they still land in the right group.

Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.

All Python programs · CBSE class 12 practical file · Python exercises