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.
Contact Us