In this article we will discuss when & how to use python’s filter() function with lambda

filter() function in python

Python provides a method to filter out contents from a given sequence that can be a list, string or tuple etc.

Arguments:

  • An iterable sequence to be filtered.
  • a function that accepts an argument and returns bool i.e. True or False based on it’s logic.

Returns:

  • A new sequence of filtered contents.

Logic:
filter() iterates over all elements in the sequence and for each element it calls the given callback function. If this function returns False then that element is skipped, whereas elements for which it returned True are added into a new list. In the end it returns a new list with filtered contents based on the function passed to it as argument.

Let’s understand by examples

Filter a list of strings in Python using filter()

Suppose we have a list of strings i.e.

Now let’s filter the contents of list and keep the strings with length 2 only using filter() i.e.

Output:

So, filter() iterated over all the strings in given list and the called isOfLengthFour() for each string element. String elements for which isOfLengthFour() returned True were kept in a separate sequence and returned.

Using filter() with Lambda function

As you can see that we have created a separate function isOfLengthFour() and passed it to filter() function. We can completely avoid the creation of these kind of one time small function by using lambda function.
Let’s pass a lambda function to filter() for selecting strings with length 2 only from the list i.e.

Output:

It worked same as the previous example but we avoided creating extra function by using a lambda function.

Filter characters from a string in Python using filter()

We can also use filter() with a string as an iterable sequence and can filter out characters from it.

Suppose we have a string i.e.

Now let’s use filter() to remove or filter all occurrences of characters ‘s’ and ‘a’ from the above string i.e.

Output:

filter() basically returned a list of characters from above string by filtered all occurrences of ‘s’ & ‘a’. Then by using join() we joined the filtered list of characters to a single string.

Filter an array in Python using filter()

Suppose we have two array i.e.

Now we want to filter the contents in array1 i.e. by removing numbers from array1 which are common in array1 and array2. For example new array should be,

Now let’s see how to do that using filter() and lambda function

Output:

It basically filtered out the elements from array1 which were present in array2.

Complete example is as follows,

Output:

If you didn't find what you were looking, then do suggest us in the comments below. We will be more than happy to add that.

Do Subscribe with us for more Articles / Tutorials like this,