Lambda and filter in Python Examples


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.

What are lambda expressions?

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:

Syntax

 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

What is the filter 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.

Syntax

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.

ILLUSTRATION 1

Example

inp_list = ['t','u','t','o','r','i','a','l']
result = list(filter(lambda x: x!='t' , inp_list))

print(result)

Output

['u', 'o', 'r', 'i', 'a', 'l']

Explanation 

Here all elements in the list other than ‘t’ are filtered by the condition and list is formed by the help of lambda expression.

ILLUSTRATION 2

Example

inp_list = [1,2,3,4,5,6,7,8,9,10]
result = list(filter(lambda x: x%2==0 , inp_list))

print(result)

Output

[2, 4, 6, 8, 10]

Explanation

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.

Conclusion

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.

Updated on: 07-Aug-2019

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements