Lambda expressions in Python
In Python, functions are defined with def
statements. You can also use lambda
to create anonymous functions. You can use lambda expressions when you need to specify a function as an argument.
- 4. More Control Flow Tools - Lambda Expressions — Python 3.11.3 documentation
- 6. Expressions - Lambdas — Python 3.11.3 documentation
See the following article for the basics of functions in Python.
Basics of lambda expressions
The function definition using the def
statement and its corresponding lambda expression are as follows.
def function_name(parameter1, parameter2, ...):
return expression
function_name = lambda parameter1, parameter2, ...: expression
For convenience, the lambda expression is assigned a name in the above example, but PEP8 does not recommend this, as described later.
The concrete example is as follows. You can also specify a default parameter value.
def add_def(a, b=1):
return a + b
add_lambda = lambda a, b=1: a + b
print(add_def(3, 4))
# 7
print(add_def(3))
# 4
print(add_lambda(3, 4))
# 7
print(add_lambda(3))
# 4
Lambda expressions with if
You cannot use multi-line statements in lambda expressions, but you can use conditional expressions.
get_odd_even = lambda x: 'even' if x % 2 == 0 else 'odd'
print(get_odd_even(3))
# odd
print(get_odd_even(4))
# even
PEP8 recommends not naming lambda expressions
If you assign a name to a lambda expression as shown in the previous examples, the code checker may issue a warning.
Do not assign a lambda expression, use a def (E731)
PEP8 (Style Guide for Python Code) recommends using lambda expressions without names and using the def
statement when defining a function with a name.
Always use a def statement instead of an assignment statement that binds a lambda expression directly to an identifier: PEP 8 – Style Guide for Python Code | peps.python.org
Since this is only a recommendation and not a strict rule, you can still execute the code without any errors even if you assign a name to a lambda expression.
Examples of lambda expressions
The key
argument of sorted()
, sort()
, max()
, min()
The built-in functions sorted()
, max()
, and min()
, along with the list method sort()
, all have a key
argument.
You can specify a function to be applied to each element of the iterable object before the elements are compared using the key
argument.
Consider the built-in sorted()
function.
The list of strings is sorted alphabetically by default.
l = ['Charle', 'Bob', 'Alice']
l_sorted = sorted(l)
print(l_sorted)
# ['Alice', 'Bob', 'Charle']
If you use the built-in len()
function, which returns the number of characters, as the key
argument, the list will be sorted according to the number of characters.
print(len('Alice'))
# 5
l_sorted_len = sorted(l, key=len)
print(l_sorted_len)
# ['Bob', 'Alice', 'Charle']
You can use a lambda expression to apply any function to each element and sort based on the result. For example, if you specify a lambda expression to get the second character as the key
argument, the list will be sorted alphabetically by the second character.
print((lambda x: x[1])('Alice'))
# l
l_sorted_second = sorted(l, key=lambda x: x[1])
print(l_sorted_second)
# ['Charle', 'Alice', 'Bob']
map()
and filter()
In map()
, which applies a function to all elements of an iterable, and filter()
, which extracts elements that satisfy a condition, the first argument is a function (callable object), and the second argument is an iterable object, such as a list.
- Apply a function to items of a list with map() in Python
- Filter (extract/remove) items of a list with filter() in Python
When specifying a function (callable object) as an argument, using a lambda expression is often simpler than defining the function with a def
statement.
Note that operations similar to map()
and filter()
can also be written using list comprehensions and generator expressions, which are often easier to use in many cases.
map()
Specify a lambda expression that squares the value as the first argument. Note that map()
returns an iterator instead of a list in Python 3.
l = [0, 1, 2, 3]
map_square = map(lambda x: x**2, l)
print(map_square)
# <map object at 0x1072fd128>
print(list(map_square))
# [0, 1, 4, 9]
If you want to get a list, you can also use list comprehension.
l_square = [x**2 for x in l]
print(l_square)
# [0, 1, 4, 9]
If you prefer to get an iterator, you can use a generator expression instead.
g_square = (x**2 for x in l)
print(g_square)
# <generator object <genexpr> at 0x1072b6d00>
print(list(g_square))
# [0, 1, 4, 9]
filter()
Specify a lambda expression that returns True
for even numbers as the first argument. filter()
returns an iterator in Python 3, just like map()
.
filter_even = filter(lambda x: x % 2 == 0, l)
print(list(filter_even))
# [0, 2]
The same operation can also be achieved using list comprehensions and generator expressions.
l_even = [x for x in l if x % 2 == 0]
print(l_even)
# [0, 2]
See the following article for details on extracting elements from a list.