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
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
num % 2is the remainder whennumis divided by 2: 0 for even numbers and 1 for odd ones.- Each number is appended to
even_numbersorodd_numbersdepending on that remainder. - The numbers keep the order they had in the original list.
len()of each list gives how many even and odd numbers there are.
Other ways to write it
Using list comprehensions
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 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.
Related programs
- Check Whether a Number Is Even or Odd
- Count Positive and Negative Numbers in a List
- Print Even Numbers in a Range
- Find the Sum of Elements in a List
- Find the Largest and Smallest Number in a List
- Swap Elements at Even and Odd Positions in a List
- Find the Second Largest Number in a List
- Remove Duplicates from a List
- a Menu-Driven List
- Reverse a List
All Python programs · CBSE class 12 practical file · Python exercises