Python Lambda Functions: When to Use (and When Not To)
Leer en españolЧитать на русскомLer em portuguêsอ่านภาษาไทย
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.
10 10
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:
10 Ada Lovelace
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."
['Bob', 'Charlie', 'alice'] ['alice', 'Bob', 'Charlie']
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:
Charlie: 72 Alice: 88 Diana: 91 Bob: 95
Mouse: $25 Keyboard: $75 Laptop: $999
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.
[2, 4, 6, 8, 10] [2, 4]
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:
[11.55, 26.39, 5.5, 49.5, 14.03] [23.99, 45.0]
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 handling['apple', 'banana', 'cherry'] ['apple', 'banana', 'cherry']
Common 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.
Alex: 30 Zara: 22
even odd
awesome is
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']
Software versions such as "1.10.2" do not sort like text: version 1.10 is newer than 1.9, but as text "1.10" comes first. Write a function sort_versions(versions) that returns a new list from oldest to newest.
sort_versions(["1.10", "1.9", "1.2"]) # ['1.2', '1.9', '1.10']The rules:
"1.2" comes before "1.2.0".v ("v2.1"). Ignore it when comparing, but return every version exactly as it was written.Some of the tests are hidden.