PublishedÖ‰ April 21, 2026

How to Use a Lambda Function in Python

Lambda functions are one of those Python features that look confusing at first but turn out to be surprisingly simple. They're small, anonymous functions you can write in a single line and use right away.

In this tutorial, you'll learn what lambda functions are, how they work, and when they're actually useful. We'll cover the most common use cases (including filter(), map(), sorted(), and pandas) so you can recognize lambda functions in real code and start using them with confidence.

What Is a Lambda Function in Python?

A lambda function is an anonymous function, meaning it doesn't have a name. It can take any number of arguments, but only evaluates a single expression, and it returns the result of that expression automatically.

The general syntax for a lambda function is: lambda parameters: expression. Here's a simple example that breaks it down:

Anatomy of a Lambda Function

You'll see the terms 'lambda expression' and 'lambda function' used interchangeably. The expression is the syntax you write; the function is the object Python creates from it. For practical purposes, they mean the same thing.

Three parts make up every lambda expression:

  • The lambda keyword, which tells Python you're defining an anonymous function (similar to def for regular functions)
  • The parameters, which work just like function parameters, separated by commas
  • The expression, which gets evaluated and returned automatically

Unlike a regular function, you don't use the return keyword. Whatever the lambda expression evaluates to is what comes back.

Lambda Functions vs. Regular Functions

Before going further, let's compare a lambda function to a regular function defined with def. This table covers the differences you'll encounter most often:

Feature Lambda Function Regular Function (def)
Naming Anonymous (no function name) Always has a function name
Syntax lambda x: x + 1 def func(x): return x + 1
Return Implicit (expression result) Usually explicit via return
Body Single expression only Multiple statements allowed
Docstrings Not supported Supported
Best for Short, one-time operations Reusable or complex logic

One thing worth calling out: you can assign a lambda to a variable, like this:

increment = lambda x: x + 1
increment(2)
# Output:
# 3

But PEP 8, Python's official style guide, recommends against it. When you assign a lambda to a variable, you're just giving an anonymous function a name, which defeats its purpose. If you need a named, reusable function, use def instead.

Lambda vs Standard Function

How Lambda Functions Work

You can call a lambda immediately by wrapping it in parentheses:

(lambda x: x + 1)(2)
# Output:
# 3

This pattern is sometimes called an immediately invoked function expression (IIFE). You define the function and call it in the same line. It's useful when you need a quick computation without storing anything.

Lambda functions also support multiple parameters. Separate them with commas, just like a regular function:

(lambda x, y, z: x + y + z)(3, 8, 1)
# Output:
# 12

A lambda can also return multiple values by wrapping them in a tuple:

(lambda x, y: (x + y, x * y))(3, 4)
# Output:
# (7, 12)

You can use conditional logic inside a lambda too. A single if/else is perfectly readable and common in practice:

(lambda x: x if x > 10 else 10)(5)
# Output:
# 10

That said, avoid nesting multiple conditions in a lambda. Compare these two approaches:

# Lambda with nested conditions (hard to read)
(lambda x: x * 10 if x > 10 else (x * 5 if x < 5 else x))(11)
# Output:
# 110
# Regular function (much clearer)
def check_conditions(x):
    if x > 10:
        return x * 10
    elif x < 5:
        return x * 5
    else:
        return x

print(check_conditions(11))
# Output:
# 110

Both return 110, but the regular function is far easier to read and maintain. When your logic needs more than one condition, reach for def.

Lambda with Built-in Functions

Lambda functions are most useful when passed directly to built-in functions. Here are the four most common pairings.

1. filter()

filter() takes a function and an iterable, and returns only the items where the function evaluates to True:

numbers = [33, 3, 22, 2, 11, 1]
result = list(filter(lambda x: x > 10, numbers))
print(result)
# Output:
# [33, 22, 11]

2. map()

map() applies a function to every item in an iterable and returns the transformed results:

numbers = [1, 2, 3, 4, 5]
result = list(map(lambda x: x * 10, numbers))
print(result)
# Output:
# [10, 20, 30, 40, 50]

One key difference from filter(): map() always returns an iterable with the same number of items as the original.

3. reduce()

reduce() applies a function cumulatively to the items of an iterable, reducing them down to a single value. You'll need to import it from the functools module:

from functools import reduce

numbers = [1, 2, 3, 4, 5]
total = reduce(lambda x, y: x + y, numbers)
print(total)
# Output:
# 15

The lambda takes two arguments at a time: the accumulated result and the next item. For common aggregations like sums or minimums, Python's built-in sum(), min(), and max() are simpler. reduce() shines when you need custom accumulation logic.

4. sorted()

sorted() returns a new sorted list. By passing a lambda to its key parameter, you can control what gets sorted on:

students = [("Alice", 88), ("Bob", 72), ("Clara", 95)]
result = sorted(students, key=lambda student: student[1])
print(result)
# Output:
# [('Bob', 72), ('Alice', 88), ('Clara', 95)]

This sorts the list of tuples by the second element (the score) rather than the first. You can sort by any computed value this way, which makes sorted() with a lambda extremely practical.

Lambda with List Comprehensions

You might encounter lambda functions inside list comprehensions:

operations = [(lambda x: x ** 2)(n) for n in [1, 2, 3, 4]]
print(operations)
# Output:
# [1, 4, 9, 16]

This works, but there's a simpler way to write it:

operations = [n ** 2 for n in [1, 2, 3, 4]]
print(operations)
# Output:
# [1, 4, 9, 16]

Same result, less complexity. In most cases, a plain list comprehension is cleaner than wrapping a lambda inside one. You're more likely to encounter this in existing code than to need it yourself, so recognize it but don't default to it.

One case where lambdas in list comprehensions do make sense is when you're building a list of functions:

multipliers = [lambda x, n=n: x * n for n in range(1, 4)]
print(multipliers[0](5))  # 5
print(multipliers[1](5))  # 10
print(multipliers[2](5))  # 15

Each lambda captures a different value of n, creating a reusable set of functions. This leads us to a related concept.

Lambda as a Function Factory (Closures)

You can return a lambda from a regular function to create specialized functions on the fly:

How Closures Work with Lambda

Here, make_multiplier() returns a lambda that "remembers" the value of n from the enclosing function. This is called a closure. Each call to make_multiplier() produces a new function with its own captured value.

This is handy when you need similar functions that differ by one parameter.

Lambda with pandas

Lambda functions pair well with pandas for quick data transformations. You'll often see them with the .apply() and .map() methods on DataFrames and Series.

Here's an example that creates a new column based on values in an existing one:

import pandas as pd

df = pd.DataFrame({"score": [45, 82, 67, 91, 38]})
df["pass_fail"] = df["score"].map(lambda x: "Pass" if x >= 60 else "Fail")
print(df)
   score pass_fail
0     45      Fail
1     82      Pass
2     67      Pass
3     91      Pass
4     38      Fail

For row-wise operations across multiple columns, use .apply() with axis=1:

df = pd.DataFrame({"first": [10, 20, 30], "second": [5, 15, 25]})
df["total"] = df.apply(lambda row: row["first"] + row["second"], axis=1)
print(df)
   first  second  total
0     10       5     15
1     20      15     35
2     30      25     55

Keep in mind that for simple arithmetic or comparisons, pandas' built-in vectorized operations (like df["score"] >= 60) are faster and more readable. Lambdas with .apply() and .map() are most useful when the transformation involves logic that can't be expressed as a single vectorized operation.

If you're working with data in Python, you'll encounter lambdas with pandas a lot. Our Advanced Data Cleaning in Python course covers more of these patterns as part of the Data Analyst and Data Scientist career paths.

Pros and Cons of Lambda Functions

Pros:

  • Compact syntax for simple, one-time operations
  • Can be passed directly to higher-order functions like filter(), map(), and sorted()
  • Can be invoked immediately (IIFE) without defining a named function
  • Useful when an API expects a short function argument

Cons:

  • Limited to a single expression (no loops, no multiple statements)
  • Nested conditions quickly become unreadable
  • Cannot include docstrings or variable assignments
  • Harder to debug because they appear as <lambda> in tracebacks instead of a descriptive function name

Best Practices

  • Keep them simple. If your lambda needs more than one line of logic, use a def function instead.
  • Don't assign lambdas to variables. PEP 8 discourages this. Define a regular function if you need to reuse it.
  • Prefer list comprehensions for simple transformations. [x ** 2 for x in numbers] is cleaner than list(map(lambda x: x ** 2, numbers)) in most situations.
  • Use lambdas inline. They're at their best when passed directly as arguments to functions like sorted(), filter(), and pandas .apply().

Wrapping Up

Lambda functions are a small but practical tool in Python. They let you write short, throwaway functions right where you need them, and they pair naturally with built-in functions and libraries like pandas. Keep them simple, use them inline, and reach for def when your logic outgrows a single expression.

If you're looking to sharpen your Python skills further, our Intermediate Python for AI Engineering course is a great next step on the AI Engineering in Python career path. And if you're focused on data science, our Advanced Data Cleaning in Python course puts lambda functions to work as part of the Data Scientist career path.

FAQs

Why is it called a lambda function?

The name comes from lambda calculus, a mathematical system for expressing computation developed in the 1930s. Python borrowed the term to describe small, anonymous functions.

Can a lambda function have multiple lines?

No. Lambda functions are limited to a single expression. If you need multiple lines of logic, conditionals, or statements like try/except, use a regular function with def.

When should I use a lambda function instead of def?

Use a lambda when you need a short, one-time function that you'll pass directly as an argument, like sorting with a custom key or filtering a list. If you plan to reuse the function or the logic is more than a single expression, def is the better choice.

Can I use lambda functions with pandas?

Yes. Lambda functions work well with pandas methods like .apply() and .map() for quick transformations on DataFrames and Series. They're a common pattern for creating new columns based on existing data.

Mike Levy

About the author

Mike Levy

Mike is a life-long learner who is passionate about mathematics, coding, and teaching. When he's not sitting at the keyboard, he can be found in his garden or at a natural hot spring.