Python lambda functions
last modified November 16, 2026 Python 3.15
In this article we show how to create anonymous functions in Python with the
lambda keyword.
A lambda function, also known as an anonymous function, is a small
function defined inline, without a name. Its body is restricted to a single
expression, whose value is returned automatically. Lambdas are typically
passed as arguments to other functions, such as key functions for sorting or
callbacks, where a full def statement would be needlessly verbose.
Lambda syntax
A lambda expression has the form lambda parameters: expression.
The parameter list follows the same rules as in a def statement:
it may be empty and may contain default values, *args, and
**kwargs.
add = lambda a, b: a + b
greet = lambda: 'hello'
power = lambda x, n=2: x ** n
total = lambda *args: sum(args)
describe = lambda **kw: ', '.join(f'{k}={v}' for k, v in kw.items())
print(add(3, 4))
print(greet())
print(power(5), power(2, 10))
print(total(1, 2, 3, 4))
print(describe(name='Lucy', age=28))
print((lambda x: x * 10)(7))
The example defines lambdas with two parameters, no parameters, a default value, and variable numbers of positional and keyword arguments.
print((lambda x: x * 10)(7))
A lambda can be called immediately where it is defined. The parentheses around the lambda are necessary.
$ python syntax_forms.py 7 hello 25 1024 10 name=Lucy, age=28 70
Lambda and def
A lambda creates the same kind of function object as a def
statement. The only differences are that the body is an expression and that
the function has no proper name.
def square(x):
return x * x
sqr = lambda x: x * x
print(square(3), sqr(4))
print(type(square) is type(sqr))
print(square.__name__, sqr.__name__)
print(list(map(lambda x: 1 / x, [4, 2, 0])))
Both functions have the function type. The name of every lambda
is <lambda>, which makes tracebacks less informative. For
the same reason, the PEP 8 style guide recommends using def
instead of assigning a lambda to a variable, as we did with
sqr.
$ python def_vs_lambda.py
9 16
True
square <lambda>
Traceback (most recent call last):
File "/home/user/python/def_vs_lambda.py", line 11, in <module>
print(list(map(lambda x: 1 / x, [4, 2, 0])))
~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/user/python/def_vs_lambda.py", line 11, in <lambda>
print(list(map(lambda x: 1 / x, [4, 2, 0])))
~~^~~
ZeroDivisionError: division by zero
Lambda with map
The map function applies a function to every item of one or more
iterables and returns an iterator of the results.
nums = [1, 2, 3, 4, 5, 6] squares = map(lambda x: x * x, nums) print(type(squares).__name__) print(list(squares)) words = ['sky', 'falcon', 'up'] print(list(map(lambda w: (w, len(w)), words))) a = [1, 2, 3] b = [10, 20, 30] print(list(map(lambda x, y: x + y, a, b))) print([x * x for x in nums])
The map function returns a lazy map object, so we
convert it to a list. With two iterables, the lambda takes two parameters,
one item from each list.
print([x * x for x in nums])
A list comprehension is often clearer than map with a lambda.
$ python lambda_map.py
map
[1, 4, 9, 16, 25, 36]
[('sky', 3), ('falcon', 6), ('up', 2)]
[11, 22, 33]
[1, 4, 9, 16, 25, 36]
Lambda with filter
The filter function returns an iterator over the items of an
iterable for which the function returns a true value.
nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] odd = filter(lambda x: x % 2, nums) print(list(odd)) words = ['', 'sky', 'cloud', '', 'up', 'rainbow'] print(list(filter(lambda w: len(w) > 3, words))) print(list(filter(None, words))) print([x for x in nums if x % 2])
The x % 2 expression is 1 for odd numbers and 0 for even ones,
so only the odd numbers pass. With None instead of a function,
filter keeps the truthy items, which removes the empty strings.
$ python lambda_filter.py [1, 3, 5, 7, 9, 11] ['cloud', 'rainbow'] ['sky', 'cloud', 'up', 'rainbow'] [1, 3, 5, 7, 9, 11]
Lambda as a sort key
The list.sort method and the sorted function have a
key parameter, a function called once for each item to compute
the value that is compared. Lambdas are the most common key functions.
users = [
{'name': 'John Doe', 'born': 1987, 'city': 'Boston'},
{'name': 'Jane Doe', 'born': 1996, 'city': 'Austin'},
{'name': 'Robert Brown', 'born': 1977, 'city': 'Boston'},
{'name': 'Lucia Smith', 'born': 2002, 'city': 'Austin'},
{'name': 'Patrick Dempsey', 'born': 1994, 'city': 'Denver'},
]
users.sort(key=lambda u: u['born'], reverse=True)
for user in users:
print(user['born'], user['name'])
print()
for u in sorted(users, key=lambda u: (u['city'], -u['born'])):
print(u['city'], u['born'], u['name'])
print()
print(sorted(users, key=lambda u: u['name'].split()[-1])[0]['name'])
print(sorted(['banana', 'Apple', 'cherry'], key=lambda s: s.lower()))
We first sort the users by the year of birth in descending order.
for u in sorted(users, key=lambda u: (u['city'], -u['born'])):
When the key returns a tuple, the items are compared by the first element, then by the second, and so on. Negating the year sorts the users of each city from the youngest to the oldest.
print(sorted(users, key=lambda u: u['name'].split()[-1])[0]['name']) print(sorted(['banana', 'Apple', 'cherry'], key=lambda s: s.lower()))
The key may compute a derived value: the last name, or the lowercase version of a word for a case-insensitive sort.
$ python lambda_sort.py 2002 Lucia Smith 1996 Jane Doe 1994 Patrick Dempsey 1987 John Doe 1977 Robert Brown Austin 2002 Lucia Smith Austin 1996 Jane Doe Boston 1987 John Doe Boston 1977 Robert Brown Denver 1994 Patrick Dempsey Robert Brown ['Apple', 'banana', 'cherry']
Lambda with min and max
The min and max functions also accept a
key function.
from dataclasses import dataclass
@dataclass(frozen=True)
class Car:
name: str
price: int
cars = [
Car('Audi', 52642), Car('Mercedes', 57127), Car('Skoda', 9000),
Car('Volvo', 29000), Car('Bentley', 350000), Car('Citroen', 21000),
Car('Hummer', 41400), Car('Volkswagen', 21601),
]
print(min(cars, key=lambda c: c.price))
print(max(cars, key=lambda c: c.price))
print(max(cars, key=lambda c: len(c.name)).name)
prices = {'apple': 1.2, 'kiwi': 0.5, 'mango': 2.4}
print(max(prices, key=lambda k: prices[k]))
print(min(prices.items(), key=lambda item: item[1]))
We find the cheapest and the most expensive cars and the car with the
longest name. With a dictionary, iteration goes over the keys, so the lambda
looks up the value of each key; alternatively, we compare the
(key, value) pairs returned by items.
$ python lambda_minmax.py
Car(name='Skoda', price=9000)
Car(name='Bentley', price=350000)
Volkswagen
mango
('kiwi', 0.5)
Lambda with reduce
The functools.reduce function combines the items of an iterable
into a single value by repeatedly applying a two-argument function.
from functools import reduce nums = [3, 5, 2, 8, 6] print(reduce(lambda acc, x: acc + x, nums)) print(reduce(lambda acc, x: acc * x, nums, 1)) print(reduce(lambda a, b: a if a > b else b, nums)) words = ['an', 'old', 'falcon'] print(reduce(lambda acc, w: acc + len(w), words, 0))
The lambda receives the accumulated value and the next item. The optional
third argument is the initial value. For sums, products, and maximums, the
built-in sum, math.prod, and max
functions are simpler.
$ python lambda_reduce.py 24 1440 8 11
Conditional expressions in lambdas
A lambda cannot contain an if statement, but it can contain a
conditional expression.
classify = lambda n: 'negative' if n < 0 else 'zero' if n == 0 else 'positive'
for n in (-3, 0, 5):
print(n, classify(n))
clamp = lambda x, lo=0, hi=10: max(lo, min(x, hi))
print(clamp(-4), clamp(7), clamp(25))
first_long = lambda words: next((w for w in words if len(w) > 4), None)
print(first_long(['sky', 'falcon', 'rainbow']), first_long(['up']))
The classify lambda chains two conditional expressions. The
clamp lambda limits a value to a range, and
first_long uses next with a generator expression to
find the first matching word.
$ python lambda_cond.py -3 negative 0 zero 5 positive 0 7 10 falcon None
Closures
A lambda can refer to variables of the enclosing scope. A lambda returned from a function keeps access to the variables of that function; it is a closure.
def make_multiplier(n):
return lambda x: x * n
double = make_multiplier(2)
triple = make_multiplier(3)
print(double(5), triple(5))
print(double.__closure__[0].cell_contents)
counter = 0
inc = lambda: counter + 1
counter = 10
print(inc())
The make_multiplier function returns lambdas that remember the
value of n. The captured variables are stored in the
__closure__ attribute.
counter = 0 inc = lambda: counter + 1 counter = 10 print(inc())
Free variables are looked up when the lambda is called, not when it is
created, so inc uses the current value 10.
$ python closures.py 10 15 2 11
The late binding pitfall
Because free variables are looked up at call time, lambdas created in a loop all see the last value of the loop variable. This is a common bug when creating callbacks, for example for GUI buttons.
funcs = [lambda: i for i in range(3)]
print([f() for f in funcs])
funcs = [lambda i=i: i for i in range(3)]
print([f() for f in funcs])
buttons = {}
for label in ('Open', 'Save', 'Quit'):
buttons[label] = lambda label=label: f'{label} clicked'
print(buttons['Open'](), buttons['Quit']())
All three lambdas in the first list return 2. The fix is to bind the current
value to a parameter with a default value, which is evaluated when the lambda
is created. The same technique is used for the command callbacks
of Tkinter buttons.
$ python late_binding.py [2, 2, 2] [0, 1, 2] Open clicked Quit clicked
Dispatch tables
A dictionary of lambdas can replace a long if/elif
chain that selects an operation.
ops = {
'+': lambda a, b: a + b,
'-': lambda a, b: a - b,
'*': lambda a, b: a * b,
'/': lambda a, b: a / b if b else float('nan'),
}
for expr in ('3 + 4', '10 / 4', '6 * 7', '1 / 0'):
a, op, b = expr.split()
print(expr, '=', ops[op](float(a), float(b)))
The operator symbol selects the lambda from the dictionary. The division lambda returns NaN instead of raising an exception for a zero divisor.
$ python dispatch.py 3 + 4 = 7.0 10 / 4 = 2.5 6 * 7 = 42.0 1 / 0 = nan
Lambdas as callbacks
Many library functions accept a function that they call at the right moment.
import re
from collections import defaultdict
text = 'Prices: 12 apples, 7 pears, 30 plums'
print(re.sub(r'\d+', lambda m: str(int(m.group()) * 2), text))
groups = defaultdict(lambda: 'unknown')
groups['admin'] = 'full access'
print(groups['admin'], groups['guest'])
scores = {'Paul': 72, 'Lucy': 91, 'Anna': 85}
print(dict(sorted(scores.items(), key=lambda kv: kv[1], reverse=True)))
The re.sub function calls the lambda for each match and replaces
the match with the returned string; here we double all numbers. The
defaultdict calls its factory lambda to create values for missing
keys. The last line sorts a dictionary by its values.
$ python callbacks.py
Prices: 24 apples, 14 pears, 60 plums
full access unknown
{'Lucy': 91, 'Anna': 85, 'Paul': 72}
Limitations of lambdas
The body of a lambda is a single expression. Statements such as
return, assignments, or if without
else are not allowed, and parameters cannot have annotations.
tests = [
'lambda x: return x',
'lambda x: y = x',
'lambda x: x if x',
'lambda x: (y := x * 2) + y',
'lambda x: print(x) or x',
'lambda x: int: x',
]
for src in tests:
try:
f = eval(src)
print(f'{src:30} ok -> {f(3)}')
except SyntaxError as e:
print(f'{src:30} SyntaxError: {e.msg}')
except NameError as e:
print(f'{src:30} NameError: {e}')
We compile several lambda expressions with eval. The assignment
expression (walrus) operator is allowed, because it is an expression. The
print(x) or x trick calls a function for its side effect and
returns x, since print returns None;
the lone 3 in the output comes from that print call.
It works, but such code is better written as a regular function.
$ python limits.py lambda x: return x SyntaxError: invalid syntax lambda x: y = x SyntaxError: invalid syntax lambda x: x if x SyntaxError: expected 'else' after 'if' expression lambda x: (y := x * 2) + y ok -> 12 3 lambda x: print(x) or x ok -> 3 lambda x: int: x SyntaxError: invalid syntax
The operator module
The operator module provides ready-made functions for the most
common lambdas: itemgetter, attrgetter, and
methodcaller.
from operator import attrgetter, itemgetter, methodcaller
from collections import namedtuple
Point = namedtuple('Point', 'x y')
points = [Point(3, 1), Point(1, 2), Point(2, 0)]
pairs = [('b', 2), ('a', 3), ('c', 1)]
print(sorted(pairs, key=lambda p: p[1]))
print(sorted(pairs, key=itemgetter(1)))
print(sorted(points, key=attrgetter('y')))
print(list(map(methodcaller('upper'), ['sky', 'sun'])))
print(list(map(str.upper, ['sky', 'sun'])))
print(itemgetter(0, 1)('abc'))
The itemgetter(1) call creates a function equivalent to
lambda p: p[1], and attrgetter('y') is equivalent to
lambda p: p.y. With several arguments, itemgetter
returns a tuple. Unbound methods such as str.upper can also be
passed directly.
$ python operator_alt.py
[('c', 1), ('b', 2), ('a', 3)]
[('c', 1), ('b', 2), ('a', 3)]
[Point(x=2, y=0), Point(x=3, y=1), Point(x=1, y=2)]
['SKY', 'SUN']
['SKY', 'SUN']
('a', 'b')
Source
Lambdas – Python language reference
Sorting techniques – Python HOWTO
In this article we have worked with lambda functions in Python. See also Python functions and Python operator module.
Author
List all Python tutorials.