filter() function facilitates a functional approach to Python programming. It takes as an argument a function and an iterable and applies the passed function to each element of the iterable. Once this is done, it returns an iterable.
filter() function is similar to a for-loop in Python but is much fast as a built-in function.
Here is the function signature for the
filter() function in Python:
# function signature for the filter() method returned_iterable = filter(function, iterable)
As described above, the
filter() function takes the following two arguments as input:
function: A valid, pre-defined function. This is a lambda function in most cases.
iterable: This is an iterable object (e.g. list, tuple, dictionary).
Returned: An iterator to the filtered items’ iterable object.
Let’s take a look at a couple of examples of how the
filter() method works:
myList = [10, 25, 17, 9, 30, -5] # Returns the elements which are multiples of 5 myList2 = list(filter(lambda n : n%5 == 0, myList)) print(myList2)
# Returns the elements which are multiples of 5 def multipleOf5(n): if(n % 5 == 0): return n myList = [10, 25, 17, 9, 30, -5] myList2 = list(filter(multipleOf5, myList)) print(myList2)
View all Courses