How to use lambda() Function with filter() In Python

The filter() function in Python takes in a function and a list as arguments. This offers an elegant way to filter out all the elements of a sequence “sequence”, for which the function returns True. Here is a small program that returns the odd numbers from an input list: 

Filter out all odd numbers using filter() and lambda function

Here, lambda x: (x % 2 != 0) returns True or False if x is not even. Since filter() only keeps elements where it produces True, thus it removes all odd numbers that generated False.

Python3




li = [5, 7, 22, 97, 54, 62, 77, 23, 73, 61]
 
final_list = list(filter(lambda x: (x % 2 != 0), li))
print(final_list)


Output:

[5, 7, 97, 77, 23, 73, 61]

Filter all people having age more than 18, using lambda and filter() function

The code filters a list of ages and extracts the ages of adults (ages greater than 18) using a lambda function and the filter' function. It then prints the list of adult ages. The output displays the ages of individuals who are 18 years or older.

Python3




ages = [13, 90, 17, 59, 21, 60, 5]
adults = list(filter(lambda age: age > 18, ages))
 
print(adults)


Output:

[90, 59, 21, 60]

Python Lambda Functions

Python Lambda Functions are anonymous functions means that the function is without a name. As we already know the def keyword is used to define a normal function in Python. Similarly, the lambda keyword is used to define an anonymous function in Python

Similar Reads

Python Lambda Function Syntax

Syntax: lambda arguments : expression This function can have any number of arguments but only one expression, which is evaluated and returned. One is free to use lambda functions wherever function objects are required. You need to keep in your knowledge that lambda functions are syntactically restricted to a single expression. It has various uses in particular fields of programming, besides other types of expressions in functions....

Python Lambda Function Example

In the example, we defined a lambda function(upper) to convert a string to its upper case using upper()....

Use of Lambda Function in Python

...

Practical Uses of Python lambda function

Let’s see some of the practical uses of the Python lambda function....

Using lambda() Function with filter()

...

Using lambda() Function with map()

...

Using lambda() Function with reduce()

Python Lambda Function with List Comprehension...

Contact Us