Python filter()

Write a program in Python to filter the given list if the given expression evaluates to true.

Suppose the list and expression are -

list = [0, 3, 2, 30, 20, 34, 89, 35, 72, 64]
expr = (x % 4 == 0)

Solution

The function filter(function, list) offers an elegant way to filter out all the elements of a list, for which the function returns true. This function will be applied to every element of the list.

Syntax of Python filter()
 filter(function, list)

Here, function is the expression applied to all elements of the list argument.

This is the following solution to filter the given list if the given expression evaluates to true -

list = [0, 3, 2, 30, 20, 34, 89, 35, 72, 64]
result = filter(lambda x: x % 4 == 0, list)
print result

Output of the above code
Python nested if statement




Related Articles

Python program for Prime Number
Odd Even Program in Python
Python program to convert Celsius to Fahrenheit
Python Convert XML to CSV
Python Text to Speech
Python send mail to multiple recipients using SMTP server
How to generate QR Code in Python using PyQRCode
Python programs to check Palindrome strings and numbers
CRUD operations in Python using MYSQL Connector
Fibonacci Series Program in Python
Python File Handler - Create, Read, Write, Access, Lock File
Python convert XML to JSON
Python convert xml to dict
Python convert dict to xml




Read more articles


General Knowledge



Learn Popular Language