Open In App

Python Program to Split the Even and Odd elements into two different lists

Last Updated : 27 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In Python, it’s a common task to separate even and odd numbers from a given list into two different lists. This problem can be solved using various methods. In this article, we’ll explore the most efficient ways to split even and odd elements into two separate lists.

Using List Comprehension

List comprehension is the most efficient way to separate even and odd numbers. It combines the looping and condition check into a single line, making the code concise and fast.

Python
a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

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

print(evens)  
print(odds)    

Output
[2, 4, 6, 8, 10]
[1, 3, 5, 7, 9]

Explanation:

  • We use two list comprehensions to directly create evens and odds.
  • The condition n % 2 == 0 checks if the number is even, and n % 2 != 0 checks if it’s odd.

Let’s explore some more methods and see how we can split the even and odd elements into two different lists.

Using filter()

filter() function can be used to filter elements from a list based on a given condition. It returns an iterator, so we need to convert it to a list using list().

Python
a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

evens = list(filter(lambda n: n % 2 == 0, a))
odds = list(filter(lambda n: n % 2 != 0, a))

print(evens)  
print(odds)    

Output
[2, 4, 6, 8, 10]
[1, 3, 5, 7, 9]

Explanation:

  • The filter() function applies the lambda function to each element of numbers.
  • The lambda checks if the number is even or odd.

Using for Loop

This is the basic method using an explicit for loop to iterate through the list and separate the even and odd numbers into two lists.

Python
a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

evens, odds = [], []

for n in a:
    evens.append(n) if n % 2 == 0 else odds.append(n)

print(evens)  
print(odds)    

Output
[2, 4, 6, 8, 10]
[1, 3, 5, 7, 9]

Explanation:

  • The for loop iterates over each element in numbers.
  • For each element, the code checks if the number is even or odd and appends it to the respective list.

Using While Loop

A while loop can also be used to iterate through the list. This method is less common and generally slower compared to for loops or list comprehensions.

Python
a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

evens, odds, i = [], [], 0

while i < len(a):
    evens.append(a[i]) if a[i] % 2 == 0 else odds.append(a[i])
    i += 1

print(evens)  
print(odds)  

Output
[2, 4, 6, 8, 10]
[1, 3, 5, 7, 9]

Explanation:

  • A while loop is used to iterate through the list numbers by maintaining an index.
  • We check if each number is even or odd and append it to the respective list.


Next Article

Similar Reads