Python Program to Put Even and Odd elements in a List into Two Different Lists

PythonServer Side ProgrammingProgramming

When it is required to place even and odd elements in a list into two different lists, a method with two empty lists can be defined. The modulus operator can be used to determine if the number is even or odd.

Below is the demonstration of the same −

Example

 Live Demo

def split_list(my_list):
   even_list = []
   odd_list = []
   for i in my_list:
      if (i % 2 == 0):
         even_list.append(i)
      else:
         odd_list.append(i)
   print("The list of odd numbers are :", even_list)
   print("The list of even numbers are :", odd_list)

my_list = [2, 5, 13, 17, 51, 62, 73, 84, 95]
print("The list is ")
print(my_list)
split_list(my_list)

Output

The list is
[2, 5, 13, 17, 51, 62, 73, 84, 95]
The list of odd numbers are : [2, 62, 84]
The list of even numbers are : [5, 13, 17, 51, 73, 95]

Explanation

  • A method named ‘split_list’ is defined, that takes a list as a parameter.

  • Two empty lists are defined.

  • The parameter list is iterated over, and the modulus operator is used to determine if the number is even or odd.

  • If it is an even number, it is added to first list, otherwise it is added to the second list.

  • This is displayed as output on the console.

  • Outside the function, a list is defined, and the method is called by passing this list.

  • The output is displayed on the console.

raja
Published on 19-Apr-2021 14:30:48
Advertisements