In this post we learn how to filter odd and even numbers from the list in python with very basic examples and explanation.
There are two ways to filter odd and even numbers from the list…
- with using filter() function (filter is built-in function in python).
- without using filter functions.
We are write program using both the ways filter() function and without using filter function.
With using filter() function
Question may asked like that: Write a python program to filter odd and even numbers from the list using filter function.
But before writing a program you should know about..
Source code:
print("Filter odd even numbers from the list!!")
num_list = [2,7,4,9,1,8]
print(f"Mixed list : {num_list}")
even_list = filter(lambda num: num % 2 == 0,num_list) # return iterator object
even_list = list(even_list) # convert into list
print(f"Even list : {even_list}")
odd_list = filter(lambda num: num % 2 != 0,num_list) # return iterator object
odd_list = list(odd_list) # convert into list
print(f"Odd list : {odd_list}")
Output:
Filter odd even numbers from the list !!
Mixed list : [2, 7, 4, 9, 1, 8]
Even list : [2, 4, 8]
Odd list : [7, 9, 1]
Without using filter function
Question may asked like that: Write program to filter odd and even numbers from a list without using filter() function in python.
we are write this program in two different ways..
- In simple way or
- by using user define function
1. Simple way
For writing program in simple way you should know about..
Source code:
my_list = [22,25,12,27,11,28,21,22]
print(f"My mixed list : {my_list}")
my_even = []
my_odd = []
for num in my_list:
if num % 2 == 0:
my_even.append(num)
else:
my_odd.append(num)
print(f"My even list : {my_even}")
print(f"My odd list : {my_odd}")
Output:
My mixed list : [22, 25, 12, 27, 11, 28, 21, 22]
My even list : [22, 12, 28, 22]
My odd list : [25, 27, 11, 21]
2. By using user define function
Question may asked like that: Write a program to filter odd and even numbers from a list by using user define function in python.
For this program you should know about..
Source code:
def filter_odd_even(num_list):
even = []
odd = []
for i in num_list:
if i % 2 == 0:
even.append(i)
else:
odd.append(i)
print(f"Even list is : {even}")
print(f"Odd list is : {odd}")
mixed_list = [10,13,11,17,14,18,20]
print(f"Mixed list is : {mixed_list} ")
filter_odd_even(mixed_list)
Output:
Mixed list is : [10, 13, 11, 17, 14, 18, 20]
Even list is : [10, 14, 18, 20]
Odd list is : [13, 11, 17]
Hope you learn something new from this post -thankyou.