image
image
image

Python Anonymous Function

image

Some functions may be specified devoid of a name and this are called anonymous function. The lambda keyword is used to denote an anonymous function. Anonymous functions are also referred to as lambda functions in Python.

Syntax

lambda arguments: expression.

Lambda functions must always have one expression but can have several arguments.

Example

Start IDLE.

Navigate to the File menu and click New Window.

Type the following:

double = lambda y: y * 2

# Output: 10

print(double(5))

Example 2

We can use inbuilt functions such as filter () and lambda to show only even numbers in a list/tuple.

Start IDLE.

Navigate to the File menu and click New Window.

Type the following:

first_marks = [3, 7, 14, 16, 18, 21, 13, 32]

fresh_marks = list(filter(lambda n: (n%2 == 0) , first_marks))

# Output: [14, 16, 18, 32]

print(fresh_marks)

Lambda function and map() can be used to double individual list items.

Example 3

Start IDLE.

Navigate to the File menu and click New Window.

Type the following:

first_score = [3, 7, 14, 16, 18, 21, 13, 32]

fresh_score = list(map(lambda m: m * 2 , first_score))

# Output: [6, 14, 28, 32, 36, 42, 26, 64]

print(fresh_score)