Q:

Extract Even and odd number from a given list in Python

belongs to collection: Python List Programs

0

In this problem, we are given a list by the user which may be the mixture of even and odd numbers and based on the concept of even and odd, we will split the list into two lists and one will contain only even numbers and another will contain only odd numbers. Before going to do this task, we will learn how to check the given number is even or odd in Python?

What are the even and odd number?

The number that can be fully divided by 2 is known as an even number and if the number is not divisible by 2 then it is known as an odd number.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Python program to check even or odd number

# taking input from the user 
n=int(input('Enter the number: '))

# checking whether it is EVEN or ODD
if n%2==0:
    print('{} is an even number.'.format(n))
else:
    print('{} is an odd number.'.format(n))

Output

RUN 1:
Enter the number: 63734
63734 is an even number.

RUN 2:
Enter the number: 9568405
9568405 is an odd number.

Algorithm to extract even and odd number from the given list

  1. Take the input in the form of a list.
  2. Create two empty lists to store the even and odd number which will be extracted from the given list.
  3. Check each element of the given list.
    1. If it is an EVEN number, then add this to one of the lists from the above-created list by using the append method.
    2. If it is an ODD number, then add this to another list from the above-created list by using the append method.
  4. Print both lists which will be our required list.

Python program to check even or odd number from the given list

# input the list
A=list(map(int,input('Enter elements of List: ').split()))

# create two empty lists to store EVEN and ODD elements
B=[]
c=[]

for j in A:
    if j%2==0:
        B.append(j)
    else:
        c.append(j)
        
print('List of even number: ',B)
print('List of odd number: ',c)

Output

Enter elements of List: 6 4 7 45 7 6 7 9 2 1
List of even number: [6, 4, 6, 2]
List of odd number: [7, 45, 7, 7, 9, 1]

append() method:

The function append use to add a number to an existing list. Here, we have used the append function to add an even number to list B and odd numbers to list C.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Python List Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Remove falsy values from a list in Python... >>
<< Find the index of an item given a list containing ...