What is the Anonymous function in Python?

Introduction:

Lambda functions are single-line functions that can take multiple arguments but have a single expression and return value.

There are three main components of the lambda function:

  • keyword: lambda
  • arguments before the colon
  • expression/return statements after colon

Lambda

  • In several programming languages, anonymous functions are introduced using the lambda keyword and anonymous functions are often referred to as lambdas or lambda abstractions.
  • Anonymous functions have been a feature of programming languages since Lisp in 1958. A growing number of modern programming languages now support anonymous functions.
  • A lambda function is a small anonymous function.
  • A lambda function can take any number of arguments, but can only have one expression. The expression is evaluated and returned.
  • Lambda functions can be used wherever function objects are required.
  • Lambda function uses the keyword lambda

Syntax:

lambda arguments: expression

svg viewer

Example:

Add 20 to an argument (a) and return the results:

x = lambda a:a+20
print(x(5))

Lambda functions can take any number of arguments:

Example 1:

Multiply argument x with argument y and return the result:

s = lambda x, y : x * y
print(s(3, 4))

Example 2:

Add the argument a,b, and c and return the result:

x = lambda a, b, c : a + b + c
print(x(3, 7, 9))

Use of Lambda Function in Python

The lambda function is commonly used with the Python built-in functions filter() and map().

Lambda with filter()

The Python built-in filter() function accepts a function and a list as an argument. It provides an effective way to filter out all the elements of the sequence and returns the new sequence whose function evaluates to True.

Example:

lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
lst1 = list(filter(lambda x:(x % 2 == 0), lst))
print(lst1)

Lambda with map()

The map() function in Python accepts a function and a list. It gives a new list that contains all modified items returned by the function for each item.

Example:

lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
lst1 = list(map(lambda x:x * 2, lst))
print(lst1)

Free Resources