26
loading...
This website collects cookies to deliver better user experience
filter()
method filters the given sequence of elements with the help of a function that tests each element in the sequence to be true or not.# function that filters vowels
from os import truncate
def even(x):
if x%2==0:
return True
else:
return False
# creating a list in Python
mylist= [3,5,1,5,7,8,2,6]
# using filter function to find even numbers
filtered = filter(even, mylist)
print('The even numbers are:')
for s in filtered:
print(s)
The even numbers are:
8
2
6
filter()
* method.# creating a list in Python
mylist= [3,5,1,5,7,8,2,6]
#filter all the odd numbers using list Comprehension
result = [x for x in mylist if x%2!=0]
print('The odd numbers are ',list(result))
#filter all the even numbers using list Comprehension
result = [x for x in mylist if x%2==0]
print('The even numbers are ',list(result))
The odd numbers are [3, 5, 1, 5, 7]
The even numbers are [8, 2, 6]
[x for x in list if condition]
. The condition can be replaced with any function which can be used as a filtering condition.# creating a list in Python
mylist= [3,5,1,5,7,8,2,6]
#filter all the odd numbers using lambda
result = filter(lambda x: x % 2 != 0, mylist)
print('The odd numbers are ',list(result))
#filter all the even numbers using lambda
result = filter(lambda x: x % 2 == 0, mylist)
print('The even numbers are ',list(result))
The odd numbers are [3, 5, 1, 5, 7]
The even numbers are [8, 2, 6]