Maintenance

Site is under maintenance — quizzes are still available.

Go to quizzes

Python Lambda Expressions

Master Python's lambda expressions — learn the syntax, when to use anonymous functions, and see practical examples. This lesson covers the core concept, step-by-step usage, and common pitfalls. Perfect for intermediate Python developers building functional programming skills.

Focus: python lambda expressions

Sponsored

You've written dozens of def functions, but every time you need a quick, one-off operation—like sorting a list of dictionaries by a key or filtering numbers—you find yourself writing a short, boilerplate function that feels heavy for the job. Python's lambda expressions solve exactly that: they let you create small, anonymous functions inline, right where you need them, without the ceremony of a full function definition. This lesson will teach you how to write lambda expressions confidently, understand their purpose, and know exactly when to use them versus a regular def function.

The problem this lesson solves

Imagine you have a list of tuples representing students and their grades, and you want to sort them by the grade (the second element). Without lambda, you'd write:

def get_grade(student):
    return student[1]

students = [("Alice", 85), ("Bob", 92), ("Charlie", 78)]
students.sort(key=get_grade)
print(students)
# Output: [('Charlie', 78), ('Alice', 85), ('Bob', 92)]

That get_grade function is small but it's defined three lines away from where it's used, breaking the flow of reading your code. As you add more small transformations—filtering, mapping, or applying simple logic—you end up cluttering your codebase with many tiny, one-purpose functions. This is the pain lambda removes: it lets you express that small function directly at the call site, making your code more concise and readable.

Core concept / mental model

A lambda expression is a small, anonymous function defined using the lambda keyword. Think of it as a function shorthand:

lambda arguments: expression
  • lambda signals you're creating a function on the fly.
  • arguments are the input parameters (like in a regular function, but without parentheses for a single argument, and with parentheses for multiple arguments).
  • expression is a single Python expression that gets evaluated and returned when the lambda is called.

💡 Key point: The expression must be a single line—no statements like if, for, or return. It's implicitly returned.

A lambda is a function object just like a def function. You can assign it to a variable (though that defeats the anonymous spirit), pass it as an argument, or use it in functional constructs like map(), filter(), and sorted().

Mental model: Picture a lambda as a portable, anonymous function generator. You write it inline, use it once (or pass it around), and it disappears. It's like a sticky note instead of a formal memo.

How it works step by step

  1. Write the lambda keyword — it tells Python you're creating an anonymous function.
  2. Specify arguments — list them after lambda, separated by commas. No parentheses needed if there's only one argument.
  3. Add a colon (:) — separates the argument list from the expression.
  4. Write the expression — a single Python expression that will be evaluated and returned when the lambda is called.
  5. Call the lambda — either immediately by placing (arguments) right after the lambda definition, or by passing it to a higher-order function.

Example: Sorting with a lambda

students = [("Alice", 85), ("Bob", 92), ("Charlie", 78)]
students.sort(key=lambda student: student[1])
print(students)
# Output: [('Charlie', 78), ('Alice', 85), ('Bob', 92)]

Here, lambda student: student[1] takes one argument student and returns student[1] (the grade). The sort method calls this lambda for each element to determine sort order.

Example: Filtering with filter()

numbers = [1, 2, 3, 4, 5, 6]
evens = list(filter(lambda x: x % 2 == 0, numbers))
print(evens)
# Output: [2, 4, 6]

The lambda returns True for even numbers, so filter() keeps them.

Example: Mapping with map()

celsius = [0, 10, 20, 30, 40]
fahrenheit = list(map(lambda c: (c * 9/5) + 32, celsius))
print(fahrenheit)
# Output: [32.0, 50.0, 68.0, 86.0, 104.0]

Hands-on walkthrough

Let's build practical understanding with a step-by-step exercise.

Exercise: Sort a list of dictionaries by a custom key

Suppose you have a list of product dictionaries, and you want to sort them by price, then by name.

products = [
    {"name": "Laptop", "price": 1200},
    {"name": "Mouse", "price": 25},
    {"name": "Keyboard", "price": 75},
    {"name": "Monitor", "price": 300},
]

# Sort by price ascending
products.sort(key=lambda p: p["price"])
print("Sorted by price:")
for product in products:
    print(f"  {product['name']}: ${product['price']}")

Expected output:

Sorted by price:
  Mouse: $25
  Keyboard: $75
  Monitor: $300
  Laptop: $1200

Now modify the lambda to sort by price descending (multiply by -1):

products.sort(key=lambda p: -p["price"])
print("Sorted by price descending:")
for product in products:
    print(f"  {product['name']}: ${product['price']}")

Expected output:

Sorted by price descending:
  Laptop: $1200
  Monitor: $300
  Keyboard: $75
  Mouse: $25

Exercise: Use min() and max() with lambdas

Find the student with the lowest and highest grade:

students = [("Alice", 85), ("Bob", 92), ("Charlie", 78)]
lowest = min(students, key=lambda s: s[1])
highest = max(students, key=lambda s: s[1])
print(f"Lowest: {lowest[0]} ({lowest[1]})")
print(f"Highest: {highest[0]} ({highest[1]})")
# Output:
# Lowest: Charlie (78)
# Highest: Bob (92)

Exercise: Use a lambda with sorted() on custom objects

If you have a class with __repr__ and want to sort instances:

class Book:
    def __init__(self, title, year):
        self.title = title
        self.year = year
    def __repr__(self):
        return f"Book({self.title!r}, {self.year})"

books = [
    Book("1984", 1949),
    Book("The Hobbit", 1937),
    Book("Dune", 1965),
]

# Sort by year
sorted_books = sorted(books, key=lambda b: b.year)
print(sorted_books)
# Output: [Book('The Hobbit', 1937), Book('1984', 1949), Book('Dune', 1965)]

Compare options / when to choose what

Feature lambda def function
Name Anonymous Named
Line count Single line Multiple lines allowed
Statements Only an expression (implicit return) Any statements, including loops, conditionals, return
Reusability Typically one-off Reused across codebase
Traceback clarity Shows <lambda> (less clear) Shows function name (clear)
When to use Short, simple logic used once Complex logic, multiple statements, or reused
Documentation Hard to docstring Easy to docstring
Performance Same as def (same underlying function object) Same as lambda

Rule of thumb: If a lambda makes your code less readable—more than a line or complex expression—use a def function instead.

Variations

  • Immediately Invoked Function Expression (IIFE) — Call a lambda right where you define it: (lambda x: x * 2)(5) returns 10. Rare in Python but possible.
  • Lambda with default arguments: lambda x, y=10: x + y — default values work as in def.
  • Lambda in data science: Often used with pandas apply() for row-wise operations: df['col'].apply(lambda x: x**2).

Troubleshooting & edge cases

Common mistake: Using statements inside a lambda

# Wrong: lambda requires an expression, not a statement
my_lambda = lambda x: if x > 0: x else -x  # SyntaxError

Fix: Use a conditional expression (ternary):

my_lambda = lambda x: x if x > 0 else -x

Common mistake: Forgetting to call list() on map()/filter()

In Python 3, map() and filter() return iterators, not lists. Without list(), you get a lazy object:

# Wrong: doesn't evaluate
result = map(lambda x: x*2, [1,2,3])
print(result)  # <map object at 0x...>
# Correct:
result = list(map(lambda x: x*2, [1,2,3]))

Edge case: Lambda captures variables by reference

If you create multiple lambdas in a loop, they'll all see the final value of the loop variable:

funcs = []
for i in range(5):
    funcs.append(lambda: i)  # all capture the same `i`
print([f() for f in funcs])  # Output: [4, 4, 4, 4, 4]

Fix: Use a default argument to capture the current value:

funcs = []
for i in range(5):
    funcs.append(lambda i=i: i)  # `i` is captured at definition
print([f() for f in funcs])  # Output: [0, 1, 2, 3, 4]

Edge case: Lambda cannot contain assignments

You cannot assign variables inside a lambda. Use a def function if you need multiple statements.

What you learned & what's next

You now understand that Python lambda expressions let you write small, anonymous functions inline for short-lived operations. You've seen how to use them with sorted(), filter(), map(), and min()/max(). You've compared lambdas with def functions and learned when each is appropriate. You've also handled common pitfalls like the loop-variable capture and the need for conditional expressions.

Next step: Move on to the next lesson in the Python track — probably list comprehensions or generator expressions, where you'll see how lambdas often pair with functional constructs to write even more expressive Python code.

Practice recap

Try this mini-exercise: Given a list of tuples data = [('apple', 3), ('banana', 1), ('cherry', 2)], write a single line using sorted() and a lambda to sort by the second element descending. Then create a new list using map() and a lambda that converts each tuple into the string 'fruit: count' (e.g., 'banana: 1'). Check your output with print().

Common mistakes

  • Using a statement inside a lambda instead of an expression (e.g., if statement rather than a conditional expression).
  • Forgetting to wrap map() or filter() with list() in Python 3 to get a list, ending up with a lazy iterator.
  • Creating lambdas inside a loop and expecting each to capture a different loop variable — they all capture the final value unless you use a default argument.
  • Trying to assign values or use return inside a lambda, which causes a syntax error.

Variations

  1. Immediately invoked function expression (IIFE) — call a lambda right after definition: (lambda x: x*2)(5).
  2. Lambdas with default arguments: lambda x, y=10: x * y.
  3. Using lambdas in data science with pandas.apply() for row-wise operations.

Real-world use cases

  • Sorting a list of user dictionaries by a nested field (e.g., 'last_login') in a web application.
  • Filtering a list of log entries to only include ERROR level entries using filter() with a lambda.
  • Transforming a pandas DataFrame column with a custom calculation applied via apply(lambda x: ...).

Key takeaways

  • Lambdas are anonymous, single-expression functions defined with lambda arguments: expression.
  • Use lambdas for short, one-off operations to make code more concise, especially with sorted(), filter(), and map().
  • Lambdas cannot contain statements (if, for, etc.) or assignments — use a conditional expression instead.
  • Prefer def for complex logic or reusable functions — readability trumps brevity.
  • Be aware of the loop-variable capture pitfall; use default arguments to fix it.
  • Lambdas are just function objects — they have the same performance as regular functions.

Sponsored

Sponsored

Discussion

Questions, corrections, and tips help everyone reading this page.

0 comments

Add a comment

Shown publicly with your comment.

Be constructive · max 4,000 characters

No comments yet — start the thread.

Related tutorials, quizzes, and articles for this topic.