In the previous article we explored how we could write a function to return the smaller elements from a list. Now we will apply similar logic to write a function to separate even and odd list elements. We are given a list, we need to write a function that takes the list as argument and returns two lists. One list that contains all the even elements of the original list while the other contains all the odd elements of the original list.
Suppose, we take the list l=[10,41,30,15,80]. It should return two lists as output:
odd = [41,15]
If the list l=[10,30,40] was provided, it would return:
even = [10,30,40]
The separation of odd and even numbers occur many times in real-life situations. Let’s say, we have a list of marks and we need to segregate the marks into two lists. The first list that contains all the students marks which are less than passing mark, and the other list which contains all the student marks which are greater than or equal to the passing mark.
Writing a program to separate Even and Odd List Elements
We are going to check for divisibility by 2 for separating the elements
def getEvenOdd(l): even=[ ] odd=[ ] for x in l: if x%2==0: even.append(x) else: odd.append(x) return even, odd l=[10,12,11,16] even, odd = getEvenOdd(l) print(even) print(odd)
Output: [10, 12, 16] 
This function takes a list as input, it creates two empty lists even and odd. It then traverses through every item in the input list and checks if it is even on condition that the number when divided by 2 it yields 0 as the remainder. If the remainder is 0 we append it to the even list or else we append it to the odd list, the function then returns both lists. Thus, we have seen how we can separate even and odd elements of a list. In the next article we will explore Comprehensions in Python.