Open In App

Filter Python list by Predicate in Python

Improve
Improve
Like Article
Like
Save
Share
Report

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




# create a list of 10 elements
data = [10, 2, 3, 4, 56, 32, 56, 32, 21, 59]
  
# apply a filter that takes only even numbers with
# lambda as predicate
a = filter(lambda x: x % 2 == 0, data)
  
# display
for i in a:
    print(i)
  
print("------------")
  
  
# apply a filter that takes only odd  numbers with
# lambda as predicate
a = filter(lambda x: x % 2 != 0, data)
  
# display
for i in a:
    print(i)


Output:

10
2
4
56
32
56
32
------------
3
21
59

Method 2: Using list comprehension

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




# create a list of 10 elements
data = [10, 2, 3, 4, 56, 32, 56, 32, 21, 59]
  
# filter data using comprehension
# to get even numbers
print([x for x in data if x % 2 == 0])
  
# filter data using comprehension
# to get odd numbers
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
Previous
Next
Share your thoughts in the comments
Similar Reads