Filter Python list by Predicate in Python
In this article, we will discuss how to filter a python list by using predicate. Filter function is used to filter the elements in the given list of elements with the help of a predicate. A predicate is a function that always returns True or False by performing some condition operations in a filter method
Syntax:
filter(predicate, list)
where,
- list is an input list
- predicate is the condition to be performed on the given list
Method 1: Using lambda as predicate
Here lambda is used to evaluate an expression that acts as a predicate.
Syntax:
filter(lambda x: condition, list)
where
- list is an input list
- condition act as predicate
Example: Filter all even numbers and odd numbers in a list
Python3
data = [ 10 , 2 , 3 , 4 , 56 , 32 , 56 , 32 , 21 , 59 ]
a = filter ( lambda x: x % 2 = = 0 , data)
for i in a:
print (i)
print ( "------------" )
a = filter ( lambda x: x % 2 ! = 0 , data)
for i in a:
print (i)
|
Output:
10
2
4
56
32
56
32
------------
3
21
59
Here list comprehension act as a predicate.
Syntax:
[iterator for iterator in list condition]
where,
- list is the input list
- iterator is used to iterate the input list of elements
- condition act as predicate
Example: Python code to get odd and even numbers
Python3
data = [ 10 , 2 , 3 , 4 , 56 , 32 , 56 , 32 , 21 , 59 ]
print ([x for x in data if x % 2 = = 0 ])
print ([x for x in data if x % 2 ! = 0 ])
|
Output:
[10, 2, 4, 56, 32, 56, 32]
[3, 21, 59]
Last Updated :
19 Dec, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...