Wednesday, July 3, 2024
HomeLanguagesPythonFilter Python list by Predicate in Python

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




# 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]

Shaida Kate Naidoo
am passionate about learning the latest technologies available to developers in either a Front End or Back End capacity. I enjoy creating applications that are well designed and responsive, in addition to being user friendly. I thrive in fast paced environments. With a diverse educational and work experience background, I excel at collaborating with teams both local and international. A versatile developer with interests in Software Development and Software Engineering. I consider myself to be adaptable and a self motivated learner. I am interested in new programming technologies, and continuous self improvement.
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments