Python Glossary Русский

all Python 3Functionsterm

lambda

lambda

An anonymous function — an expression that produces a function. Its body is a single expression.

Syntax

lambda параметры: выражение

The main trap is late binding: a lambda created inside a loop captures the variable itself, not its current value, so every such function ends up seeing the loop's final value. PEP 8 discourages binding a lambda to a name (sq = lambda...) — use def for a named function; lambda shines as a throwaway argument to key=, map() or filter().

Examples

sq = lambda x: x ** 2
print(sq(4))  # → 16
add = lambda a, b: a + b
print(add(3, 5))  # → 8
words = ['banana', 'apple', 'cherry']
words.sort(key=lambda w: len(w))
print(words)  # → ['apple', 'banana', 'cherry']
nums = [1, -2, 3, -4]
pos = list(filter(lambda x: x > 0, nums))
print(pos)  # → [1, 3]
doubled = list(map(lambda x: x * 2, [1,2,3]))
print(doubled)  # → [2, 4, 6]
pairs = [(1,'b'),(2,'a'),(3,'c')]
pairs.sort(key=lambda p: p[1])
print(pairs)  # → [(2,'a'),(1,'b'),(3,'c')]
# Вложенная lambda (каррирование)
mul = lambda x: lambda y: x * y
double = mul(2)
print(double(5))  # → 10

See also

Open in the full glossarydocs.python.orgReport an inaccuracy