Q:

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

0

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)

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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

[ 0 , 20 , 72 , 64 ]

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Python Exercises, Practice Questions and Solutions

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Write a Python program to count the occurrences of... >>
<< Write a program in Python to calculate the Fahrenh...