Skip to main content
Editor

Python Lambda Functions: When to Use (and When Not To)

Intermediate20 min6 exercises100 XP

Leer en españolЧитать на русскомLer em portuguêsอ่านภาษาไทย

0/6 exercises

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.

Lambda vs def: same result
# Regular function
def double(x):
return x * 2
# Same thing as a lambda
double_lambda = lambda x: x * 2
print(double(5))
print(double_lambda(5))
Output
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:

Lambda with multiple parameters
add = lambda a, b: a + b
print(add(3, 7))
full_name = lambda first, last: first + ' ' + last
print(full_name('Ada', 'Lovelace'))
Output
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."

Case-insensitive sorting with lambda
names = ['Charlie', 'alice', 'Bob']
# Default sort is case-sensitive (uppercase first)
print(sorted(names))
# Sort by lowercase version (case-insensitive)
print(sorted(names, key=lambda name: name.lower()))
Output
['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:

Sort tuples by second element
students = [
('Alice', 88),
('Bob', 95),
('Charlie', 72),
('Diana', 91),
]
# Sort by grade (second element)
by_grade = sorted(students, key=lambda s: s[1])
for name, grade in by_grade:
print(name + ': ' + str(grade))
Output
Charlie: 72
Alice: 88
Diana: 91
Bob: 95
Sort dictionaries by a field
products = [
{'name': 'Laptop', 'price': 999},
{'name': 'Mouse', 'price': 25},
{'name': 'Keyboard', 'price': 75},
]
# Sort by price, cheapest first
by_price = sorted(products, key=lambda p: p['price'])
for item in by_price:
print(item['name'] + ': $' + str(item['price']))
Output
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.

map() and filter() with lambdas
numbers = [1, 2, 3, 4, 5]
# Double every number
doubled = list(map(lambda x: x * 2, numbers))
print(doubled)
# Keep only even numbers
evens = list(filter(lambda x: x % 2 == 0, numbers))
print(evens)
Output
[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:

Practical map and filter
prices = [10.50, 23.99, 5.00, 45.00, 12.75]
# Add 10% tax to each price
with_tax = list(map(lambda p: round(p * 1.1, 2), prices))
print(with_tax)
# Filter prices over $20
expensive = list(filter(lambda p: p > 20, prices))
print(expensive)
Output
[11.55, 26.39, 5.5, 49.5, 14.03]
[23.99, 45.0]
Lambda with map/filter
doubled = list(map(
    lambda x: x * 2, numbers
))
evens = list(filter(
    lambda x: x % 2 == 0, numbers
))
List comprehension (often preferred)
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:

  • You need a tiny function for a key=, map(), or filter() argument
  • The logic fits in one simple expression
  • You won't reuse the function elsewhere
  • Use def when:

  • The logic needs more than one expression
  • You need if/else statements, loops, or error handling
  • You want a descriptive name for documentation
  • You'll reuse the function in multiple places
  • Simple vs complex sorting logic
    # Lambda: fine for simple key functions
    words = ['banana', 'apple', 'cherry']
    print(sorted(words, key=lambda w: len(w)))
    # def: better when logic is complex
    def sort_key(word):
    '''Sort by length, then alphabetically.'''
    return (len(word), word)
    print(sorted(words, key=sort_key))
    Output
    ['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.

    Pattern: Sort list of dicts
    # Pattern 1: Sort by dictionary key
    people = [{'name': 'Zara', 'age': 22}, {'name': 'Alex', 'age': 30}]
    by_name = sorted(people, key=lambda p: p['name'])
    for p in by_name:
    print(p['name'] + ': ' + str(p['age']))
    Output
    Alex: 30
    Zara: 22
    Pattern: Conditional lambda
    # Pattern 2: Conditional expression in lambda
    classify = lambda x: 'even' if x % 2 == 0 else 'odd'
    print(classify(4))
    print(classify(7))
    Output
    even
    odd
    Pattern: max/min with key
    # Pattern 3: Using max/min with a key
    words = ['python', 'is', 'awesome']
    longest = max(words, key=lambda w: len(w))
    print(longest)
    shortest = min(words, key=lambda w: len(w))
    print(shortest)
    Output
    awesome
    is

    Practice Exercises

    Predict the Lambda Output
    Predict Output

    What does this code print? Type the exact output.

    operation = lambda a, b: a * b + 1
    print(operation(3, 4))
    print(operation(0, 10))
    operation = lambda a, b: a * b + 1
    print(operation(3, 4))
    print(operation(0, 10))
    Sort by Last Character
    Write Code

    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']

    words = ['hello', 'world', 'python', 'code']
    # Sort by last character and print
    Filter and Transform
    Write Code

    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]

    numbers = [3, 15, 7, 20, 8, 12]
    # Filter numbers > 10, then square them
    Sort Students by GPA
    Write Code

    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.2
    students = [('Alice', 3.5), ('Bob', 3.9), ('Charlie', 3.2), ('Diana', 3.7)]
    # Sort by GPA (highest first) and print
    Sort Words by Length
    Write Code

    Given 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']

    words = ['fig', 'apple', 'date', 'kiwi', 'banana', 'pear', 'plum']
    # Sort by length, then alphabetically
    Sort Version Numbers
    Stretch

    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:

  • Compare the parts between the dots as numbers, from left to right.
  • When one version runs out of parts and everything so far is equal, the shorter one is older: "1.2" comes before "1.2.0".
  • Some versions start with a v ("v2.1"). Ignore it when comparing, but return every version exactly as it was written.
  • Versions that compare equal keep the order they had in the list.
  • Some of the tests are hidden.

    def sort_versions(versions):
    pass
    Solution unlocks after your first Check

    Harder problems

    More problems on this topic: Functions

    Related Tutorials

    Was this tutorial helpful?