Separate odd and even number in a list to different two list
- Home
- Find elements
- Separate odd and even number in a list to different two list
- On
- By
- 0 Comment
- Categories: Find elements
Separate odd and even number in a list to different two list
Separate odd and even numbers in a list into two different lists:
In this tutorial, we will discuss about separating odd and even numbers in a list into two different list.
When you divide a number by two and if the balance is zero, it is an even number.
When a number is divided by two with a remaining balance of 1, then it’s an odd number.
Example of even number 2,4,6,8,…..
Example of odd number 1,3,5,7,…..
Here, we will use a modular operator to display odd or even numbersFirst.
if n%2==0, n is a even number
if n%2==1, n is a odd number
Program 1
Approach
- To begin with, the user can allocate a length of the list of numbers using input() function.
- Then, it is initialized by a list called “NumberList=[] ” which doen’t have any numbers.
- Next, “for loop” is used to insert the numbers into the list.
- The”For loop” is then used to append each number to the list NumberList=[].
- Next, create two empty list: evenList=[] and oddList=[] for storage of even and odd numbers following separating from the initial mixed list
- then, another “for loop” checks whether the number is even or odd in the list through a modular operator.
- finally, odd and even numbers are displayed into the different list
if n%2==0, n is an even number, it is saved into an evenList=[]
if n%2==1, n is an odd number, it is saved into an oddList=[]
Program
numbers=[] #Create a empty list for store number from user input num=int(input("Enter number of elements: ")) for i in range(1,num+1): listElements=int(input("Enter telement %d: "%i)) numbers.append(listElements) evenList=[] #list for store even number oddList=[] #list for store odd number for j in numbers: if j%2==0: evenList.append(j) else: oddList.append(j) print("Even number list: ",evenList)#display separated even number list print("Odd number list: ",oddList) #display separated odd number list
When the above code is executed, it produces the following results
Enter number of elements: 7 Enter telement 1: 25 Enter telement 2: 46 Enter telement 3: 67 Enter telement 4: 78 Enter telement 5: 89 Enter telement 6: 90 Enter telement 7: 87 Even number list: [46, 78, 90] Odd number list: [25, 67, 89, 87]
Suggested for you
if statements in Python language
Similar post
Python program check whether a number is odd or even
Python program to check a number is even or odd using the function
Python program to display even and odd numbers without if
Python program to display even and odd number in the given range
Python code to display all even and odd numbers from 1 to n