Skip to main content

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

Intermediate20 min5 exercises70 XP
0/5 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
Loading editor...

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
Loading editor...

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
Loading editor...

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
Loading editor...
Sort dictionaries by a field
Loading editor...

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
Loading editor...

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
Loading editor...
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
    Loading editor...

    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
    Loading editor...
    Pattern: Conditional lambda
    Loading editor...
    Pattern: max/min with key
    Loading editor...

    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))
    Loading editor...
    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: ['code', 'world', 'python', 'hello']

    Loading editor...
    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]

    Loading editor...
    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
    Loading editor...
    Word Length Classifier
    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']

    Loading editor...