The lambda
keyword creates an inline function that contains a single expression. The value of this expression is what the function returns when invoked.
Consider the function:
def greeting():
return "Hello"
which, when called as:
print(greeting())
prints:
Hello
This can be written as a lambda function as follows:
greet_me = lambda: "Hello"
See note at the bottom of this section regarding the assignment of lambdas to variables. Generally, don't do it.
This creates an inline function with the name greet_me
that returns Hello
. Note that you don't write return
when creating a function with lambda. The value after :
is automatically returned.
Once assigned to a variable, it can be used just like a regular function:
print(greet_me())
prints:
Hello
lambda
s can take arguments, too:
strip_and_upper_case = lambda s: s.strip().upper()
strip_and_upper_case(" Hello ")
returns the string:
HELLO
They can also take arbitrary number of arguments / keyword arguments, like normal functions.
greeting = lambda x, *args, **kwargs: print(x, args, kwargs)
greeting('hello', 'world', world='world')
prints:
hello ('world',) {'world': 'world'}
lambda
s are commonly used for short functions that are convenient to define at the point where they are called (typically with sorted
, filter
and map
).
For example, this line sorts a list of strings ignoring their case and ignoring whitespace at the beginning and at the end:
sorted( [" foo ", " bAR", "BaZ "], key=lambda s: s.strip().upper())
# Out:
# [' bAR', 'BaZ ', ' foo ']
Sort list just ignoring whitespaces:
sorted( [" foo ", " bAR", "BaZ "], key=lambda s: s.strip())
# Out:
# ['BaZ ', ' bAR', ' foo ']
Examples with map
:
sorted( map( lambda s: s.strip().upper(), [" foo ", " bAR", "BaZ "]))
# Out:
# ['BAR', 'BAZ', 'FOO']
sorted( map( lambda s: s.strip(), [" foo ", " bAR", "BaZ "]))
# Out:
# ['BaZ', 'bAR', 'foo']
Examples with numerical lists:
my_list = [3, -4, -2, 5, 1, 7]
sorted( my_list, key=lambda x: abs(x))
# Out:
# [1, -2, 3, -4, 5, 7]
list( filter( lambda x: x>0, my_list))
# Out:
# [3, 5, 1, 7]
list( map( lambda x: abs(x), my_list))
# Out:
[3, 4, 2, 5, 1, 7]
One can call other functions (with/without arguments) from inside a lambda function.
def foo(msg):
print(msg)
greet = lambda x = "hello world": foo(x)
greet()
prints:
hello world
This is useful because lambda
may contain only one expression and by using a subsidiary function one can run multiple statements.
NOTE
Bear in mind that PEP-8 (the official Python style guide) does not recommend assigning lambdas to variables (as we did in the first two examples):
Always use a def statement instead of an assignment statement that binds a lambda expression directly to an identifier.
Yes:
def f(x): return 2*x
No:
f = lambda x: 2*x
The first form means that the name of the resulting function object is specifically
f
instead of the generic<lambda>
. This is more useful for tracebacks and string representations in general. The use of the assignment statement eliminates the sole benefit a lambda expression can offer over an explicitdef
statement (i.e. that it can be embedded inside a larger expression).