In this article, we will learn about lambda expressions and filter() functions in Python 3.x. Or earlier. These functions are present in the built-in Python standard library.
An inline function may be defined by the help of lambda expressions. A lambda expression consists of the lambda keyword followed by a comma seperated list of arguments and the expression to be evaluated using the list of arguments in the following format:
Lambda arguments: expression
Return value: The value computed by substituting arguments in the expressions.
Lambda expressions are often abbreviated by the name of anonymous functions as they are not given any name. Here no def keyword dis required for the declaration of function
Python provides a function filter() that takes a function and an iterable object as the input arguments and returns only those elements from the iterable object for which the function returns True.
filter(function , <list type>)
Return Type: a list of computed values
Let us look at some Illustration to get a better overview abut their implementation.
inp_list = ['t','u','t','o','r','i','a','l'] result = list(filter(lambda x: x!='t' , inp_list)) print(result)
['u', 'o', 'r', 'i', 'a', 'l']
Here all elements in the list other than ‘t’ are filtered by the condition and list is formed by the help of lambda expression.
inp_list = [1,2,3,4,5,6,7,8,9,10] result = list(filter(lambda x: x%2==0 , inp_list)) print(result)
[2, 4, 6, 8, 10]
Here we filter out all the even elements from the given list and display in the form of the list by typecasting the returned value.
In this article, we learnt how to implement the lambda and filter() functions in Python 3.x. Or earlier. We also learnt about the combined usage of both functions to get the desired output.
These functions are often used together as they provide a better way to filter out output in the desired format.