Python Lambda Functions
In this page:
lambda parameters: expression
function_name = lambda parameter: expression
What is a Lambda Function?
A lambda defines a small, unnamed function inline using the lambda keyword instead of def — it can take any number of arguments but is limited to a single expression, with no statements or multiple lines allowed.
Example: What is a Lambda Function?
square = lambda x: x * x
print(square(5))
Lambdas with filter()
filter() keeps only the items from an iterable for which a given function returns True, and a lambda is the typical way to supply that test condition inline without defining a separate named function just for one use.
Example: Lambdas with filter()
numbers = [1, 2, 3, 4, 5, 6]
evens = list(filter(lambda x: x % 2 == 0, numbers)) # keep only numbers where the lambda returns True
print(evens)
Lambdas with map()
map() applies a function to every item in an iterable and returns the transformed results; pairing it with a lambda lets you write a quick, throwaway conversion — like doubling every number in a list — without a full function definition.
Example: Lambdas with map()
numbers = [1, 2, 3]
doubled = list(map(lambda x: x * 2, numbers)) # applies the lambda to every item
print(doubled)
Lambdas with sorted()
Passing key=lambda x: x[1] to sorted() tells it to sort by a computed value rather than the item itself, which is essential when sorting tuples, dictionaries, or objects by something other than their natural order.
Example: Lambdas with sorted()
pairs = [(1, "b"), (2, "a")]
sorted_pairs = sorted(pairs, key=lambda x: x[1]) # sort by each tuple's second element
print(sorted_pairs)
Lambdas vs Regular Functions
Lambdas are meant for short, single-expression logic; the moment you need a loop, error handling, or more than one statement, a regular def function is clearer and should be preferred over forcing that logic into a lambda.
Example: Lambdas vs Regular Functions
# Lambda: short, single expression
square = lambda x: x * x
# Regular function: clearer for multi-step logic
def square_verbose(x):
result = x * x
return result
print(square(4), square_verbose(4))
- Writing statements inside a
lambda, such aslambda x: return x + 1, which is aSyntaxError; only a single expression is allowed. - Creating lambdas in a loop that use the loop variable, e.g.
lambda: i, so all of them see its final value. - Forgetting to wrap
mapandfilterresults inlist(), so printing them shows an iterator object.
Chapter Quiz — Complete all 9 topics to unlock
0/9 topics done
Complete these topics first: