Python Anonymous/Lambda Function

Ankur Agarwal
1 min readApr 20, 2021

Lambda functions are anonymous, they have no names. It’s a one-line function.

Syntax of Lambda Function in python

lambda arguments: expression

Where

lambda: is a keyword

arguments: all the parameters which we need in the expression

expression: python expression to compute the return value

Note: lambda always returns only one value.

Examples:

  1. lambda function with one argument

x = lambda a : a + 10
print(x(15))

Output is: 25

2. lambda function with 2 arguments.

x = lambda a, b : a * b
print(x(2, 4))

Output is: 8

3. lambda function with 3 arguments.

x = lambda a, b, c : a * b * c
print(x(1, 2, 3))

output is: 6

# Arguments

Like a normal function object defined with def, Python lambda expressions support all the different ways of passing arguments. This includes:

Positional arguments

(lambda a, b, c: a+ b+ c)(1, 2, 3)

Output is: 6
Named arguments (sometimes called keyword arguments)

(lambda a,b,c=4: a + b+ )(2, 3)

output is: 9
Variable list of arguments (often referred to as varargs)

(lambda a,b,c=4: a + b+ c)(2, b=3)

Output is: 9
Variable list of keyword arguments

(lambda *args: sum(args))(1,2,3,4,5)

Output is: 15
Keyword-only arguments

(lambda **kwargs: sum(kwargs.values()))(one=1, two=2, three=3)

Output is: 6

--

--