Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python lambda (Anonymous Function)

Python lambda (Anonymous Function)

Python uses lambda to create anonymous functions.

A lambda function is a small, anonymous, inline function. It can have any number of arguments, but only one expression.

An anonymous function does not require using the def keyword to define a complete function.

Lambda functions are typically used to write simple, single-line functions, often used when a function needs to be passed as an argument, such as in functions like map(), filter(), reduce(), etc.

Lambda function features:

Lambda syntax format:

lambda arguments: expression

The following lambda function takes no arguments:

Example

f

=

lambda

:

"

Hello, world!

"

print

(

f

(

)

)

Output: Hello, world!

The output is:

Hello, world!

The following example uses lambda to create an anonymous function, set a function parameter a, compute a plus 10, and return the result:

Example

x

=

lambda

a

:

a

10

print

(

x

(

5

)

)

The output is:

15

Lambda functions can also take multiple arguments, separated by commas ,:

The following example uses lambda to create an anonymous function, with function parameters a and b multiplied, and return the result:

Example

x

=

lambda

a

,

b

:

a

b

print

(

x

(

5

,

6

)

)

The output is:

30

The following example uses lambda to create an anonymous function, with function parameters a, b, and c added together, and return the result:

Example

x

=

lambda

a

,

b

,

c

:

a

b

c

print

(

x

(

5

,

6

,

2

)

)

The output is:

13

Lambda functions are often used together with built-in functions such as map(), filter(), and reduce() to perform operations on collections. For example:

Example

numbers

=

[

1

,

2

,

3

,

4

,

5

]

squared

=

list

(

map

(

lambda

x

:

x

**

2

,

numbers

)

)

print

(

squared

)

Output: [1, 4, 9, 16, 25]

The output is:

[1, 4, 9, 16, 25]

Use a lambda function together with filter() to filter even numbers:

Example

numbers

=

[

1

,

2

,

3

,

4

,

5

,

6

,

7

,

8

]

even_numbers

=

list

(

filter

(

lambda

x

:

x

%

2

==

0

,

numbers

)

)

print

(

even_numbers

)

Output: [2, 4, 6, 8]

The output is:

[2, 4, 6, 8]

The following demonstrates how to use reduce() and a lambda expression to compute the cumulative product of a sequence:

Example

from

functools

import

reduce

numbers

=

[

1

,

2

,

3

,

4

,

5

]

Use reduce() and a lambda function to compute the product

product

=

reduce

(

lambda

x

,

y

:

x

y

,

numbers

)

print

(

product

)

Output: 120

The output is:

120

In the example above, the reduce() function iterates through the numbers list and continuously updates the accumulated result using the lambda function, finally obtaining the result 1 * 2 * 3 * 4 * 5 = 120.