A Python lambda
function is a function that has one expression but can take any number of arguments. It is a small anonymous function that is subject to a more restrictive but concise syntax than regular Python functions.
lambda arguments : expression
a = lambda x, y : x * y print(a(5, 6))
The example above multiplies arguments x
and y
and returns the result, 30
.
lambda
An anonymous function is a function without a name. In Python, an anonymous function is created with the lambda
keyword, which may or may not be assigned a name.
For example, consider a two-argument anonymous function that is defined with lambda
but is not bound to a variable. The lambda
is not given a name. The function below defines a lambda
expression, takes two arguments, and returns their sum.
lambda a, b : a + b
A Python lambda
function is a single-line expression in contrast to other regular functions. Although you can spread the expression over multiple lines using parentheses or multi-line strings, it still remains a single-line expression.
The example below returns the even
string when the lambda
argument is even, and odd
when the argument is odd.
(lambda x: (x % 2 and 'even' or 'odd'))
The lambda
function supports all the different ways of passing arguments, such as a normal function object defined with the def
keyword.
This includes:
>>> (lambda a, b, c: a + b + c) (1, 2, 3) 6
>>> (lambda *args: sum(args))(1,2,3) 6
>>> (lambda **kwargs: sum(kwargs.values()))(one=1, two=2, three=3) 6
>>> (lambda x, *, y=0, z=0: x + y + z)(1, y=2, z=3) 6
lambda
expression allows the same function definition to make two or more functions in the same program.
def myfunc(x): return lambda a : a * x mydoubler = myfunc(3) mytripler = myfunc(4) print(mydoubler(11)) print(mytripler(11))
This shot summarizes Python lambda
functions, using lambda
as an anonymous function, and writing lambda
as a normal Python function.
RELATED TAGS
CONTRIBUTOR
View all Courses