Study guide · Python
Python Lambda Functions: Syntax, Use Cases & Limitations
Lambda creates a small anonymous function in one line. Useful with map, filter, and sorted — but limited by design. Here's what exams test.
Lambda syntax
A lambda is a single-expression anonymous function. It can take any number of arguments but the body must be a single expression — no statements, no assignments.
# lambda arguments: expression
square = lambda x: x ** 2
print(square(5)) # 25
add = lambda a, b: a + b
print(add(3, 4)) # 7
# Equivalent def form:
def add(a, b):
return a + bUsing lambda with sorted()
sorted() accepts a key= function. Lambda is the most common way to provide a one-line sort key.
people = [('Alice', 30), ('Bob', 25), ('Carol', 35)]
# Sort by age (second element)
by_age = sorted(people, key=lambda p: p[1])
print(by_age)
# [('Bob', 25), ('Alice', 30), ('Carol', 35)]
# Sort strings by length, then alphabetically
words = ['banana', 'fig', 'apple', 'kiwi']
result = sorted(words, key=lambda w: (len(w), w))
print(result) # ['fig', 'kiwi', 'apple', 'banana']Using lambda with map() and filter()
map() applies a function to each item; filter() keeps items where the function returns True. Both return lazy iterators.
nums = [1, 2, 3, 4, 5] doubled = list(map(lambda x: x * 2, nums)) print(doubled) # [2, 4, 6, 8, 10] evens = list(filter(lambda x: x % 2 == 0, nums)) print(evens) # [2, 4] # Modern alternative — list comprehensions are usually clearer doubled = [x * 2 for x in nums] evens = [x for x in nums if x % 2 == 0]
def instead if you need to reuse the function.Conditional expression inside lambda
You can use the ternary x if condition else y expression inside a lambda — but not an if statement.
# Ternary expression IS an expression — allowed in lambda clamp = lambda x, lo, hi: lo if x < lo else (hi if x > hi else x) print(clamp(5, 0, 10)) # 5 print(clamp(-3, 0, 10)) # 0 print(clamp(15, 0, 10)) # 10
Limitations of lambda
Lambda is intentionally restricted. These limitations frequently appear on exams.
# These are ILLEGAL inside a lambda: # f = lambda x: x = x + 1 # assignment — SyntaxError # f = lambda x: return x # return keyword — SyntaxError # f = lambda x: if x > 0: x # if statement — SyntaxError # Multiple expressions are not possible: # f = lambda x: x + 1; x * 2 # only x * 2 would be the body # Use def instead when you need any of the above
map(lambda x: x*2, lst) (returns an iterator, not a list) and [x*2 for x in lst] (returns a list directly).Want a person to help?
Struggling with Python? Work 1:1 with a vetted Python tutor on Wyzant. (affiliate link)
Find a Python tutor →