Python Lambda Functions: When to Use (and When Not To)
Imagine you need to leave someone a quick note: "Back in 5 minutes." You wouldn't write a formal letter with a greeting, three paragraphs, and a signature. You'd scribble it on a sticky note and be done.
Lambda functions are Python's sticky notes. They're tiny, anonymous, throwaway functions for when you need a quick one-liner and a full def block would be overkill.
In this tutorial, you'll learn how to write lambda functions, where they shine (sorting, filtering, mapping), and, just as importantly, when you should skip them and use a regular function instead.
How to Write a Lambda Function
A lambda function is created with the lambda keyword, followed by parameters, a colon, and a single expression. That expression is automatically returned, no return keyword needed.
The syntax is: lambda parameters: expression. There's no function name (that's why they're called "anonymous"), no def, no return, and no multi-line body. Just one expression that gets evaluated and returned.
Lambdas can take multiple parameters, just like regular functions:
Using Lambda with sorted()
The most common use of lambda functions is as the key argument in sorted(). The key parameter tells Python: "before comparing items, transform each one with this function."
The lambda lambda name: name.lower() tells sorted() to compare the lowercase versions of each string. The original strings stay unchanged, the lambda only affects the comparison.
Lambdas are especially useful for sorting complex data like lists of tuples or dictionaries:
Using Lambda with map() and filter()
map() applies a function to every item in a list and gives you back the transformed results. filter() keeps only the items where the function returns True. Both accept a function as their first argument, a perfect spot for a lambda.
We wrap map() and filter() in list() because they return lazy iterators, not lists. The list() call forces them to produce all the results at once.
Here's a more practical example, extracting and filtering data:
doubled = list(map(
lambda x: x * 2, numbers
))
evens = list(filter(
lambda x: x % 2 == 0, numbers
))doubled = [x * 2 for x in numbers]
evens = [x for x in numbers
if x % 2 == 0]Lambda vs def: When to Use Each
Lambdas are tempting because they feel clever and compact. But they have real limitations. Here's when to use each:
Use lambda when:
key=, map(), or filter() argumentUse def when:
if/else statements, loops, or error handlingCommon Lambda Patterns
Here are a few patterns you'll see in real Python code. Recognizing them will help you read other people's code and know when a lambda is the right tool.
Practice Exercises
What does this code print? Type the exact output.
operation = lambda a, b: a * b + 1
print(operation(3, 4))
print(operation(0, 10))Given a list of words, use sorted() with a lambda to sort them by their last character. Print the resulting sorted list.
Use this list: words = ['hello', 'world', 'python', 'code']
Expected output: ['world', 'code', 'python', 'hello']
Given a list of numbers, use filter() with a lambda to keep only numbers greater than 10, then use map() with a lambda to square each remaining number. Print the final list.
Use this list: numbers = [3, 15, 7, 20, 8, 12]
Expected output: [225, 400, 144]
Given a list of student tuples (name, gpa), sort them by GPA from highest to lowest using sorted() with a lambda. Print each student on a separate line in the format name: gpa.
Use this list:
students = [('Alice', 3.5), ('Bob', 3.9), ('Charlie', 3.2), ('Diana', 3.7)]Expected output:
Bob: 3.9
Diana: 3.7
Alice: 3.5
Charlie: 3.2Given a list of words, use sorted() with a lambda to sort them by length (shortest first). If two words have the same length, they should appear in alphabetical order. Print the sorted list.
Use this list: words = ['fig', 'apple', 'date', 'kiwi', 'banana', 'pear', 'plum']
Expected output: ['fig', 'date', 'kiwi', 'pear', 'plum', 'apple', 'banana']