Academic Block

Python Lambda FunctionsGet Certified

What Is a Lambda Function in Python?

A lambda function is a small, unnamed function written in a single line. Instead of using def, a name, and a return statement, you write the keyword lambda, the parameters, a colon, and one expression. Python calculates the expression and returns the result automatically.

Lambdas are most useful when you need a quick throwaway function for just one job, such as telling sorted() how to order a list. They are not more powerful than regular functions. They are simply shorter, and they can be passed around like any other value. This lesson shows when a lambda makes code clearer and when a normal function is the better choice.

  • Syntax: lambda parameters: expression creates a function object.
  • Anonymous: a lambda has no name unless you assign it to a variable.
  • One expression only: a lambda cannot contain statements such as if blocks, loops, or assignments.
  • Automatic return: the value of the expression is returned without writing return.
  • Works with key functions: sorted(), min(), max(), map(), and filter() accept lambdas.
  • Same rules as functions: lambdas support multiple parameters, default values, and closures.

From def to lambda

The easiest way to understand a lambda is to compare it with the regular function that does the same job. Every lambda can be rewritten as a def function with a single return line. The parameters go before the colon, and the result goes after it.

You can store a lambda in a variable and call it like a normal function. You can also call a lambda immediately by wrapping it in parentheses and adding the arguments. Python’s style guide, however, recommends using def when you want to give a function a name, because named functions show up clearly in error messages.

Try It: Square a Number Two Ways

Click Test My Code to run the program. Then change the numbers and run it again.

What this code does: It writes the same squaring function with def and with lambda, prints both results, and then calls a lambda immediately to add two numbers.
def square(n):
    return n * n
square_lambda = lambda n: n * n
print(square(7))
print(square_lambda(7))
print((lambda a, b: a + b)(3, 4))

Multiple Parameters, Defaults, and Conditions

A lambda can take as many parameters as you need, separated by commas, and parameters can have default values just like in a def function. You cannot write a full if statement inside a lambda, but you can use the one-line conditional expression: value_a if condition else value_b.

This combination is enough for many small jobs, such as calculating a tip or labeling a temperature. If the logic needs more than one condition or several steps, switch to a regular function. A lambda that is hard to read defeats its own purpose.

Try It: Calculate Tips and Weather Labels

Click Test My Code. Then change the bill amount or the temperature limit.

What this code does: It defines a lambda with a default tip percentage of 15%, and a second lambda that labels a temperature as "Hot" or "Comfortable" for Phoenix summer weather.
tip = lambda bill, percent=15: round(bill * percent / 100, 2)
print(tip(40))
print(tip(40, 20))
label = lambda temp: "Hot" if temp >= 85 else "Comfortable"
print(label(97))
print(label(72))

Sorting with a Lambda key

The most common use of a lambda is the key argument of sorted(), list.sort(), min(), and max(). The key function is called once for every item, and Python then orders the items by the value the key returns. It does not change the items themselves.

This is very handy for lists of tuples or dictionaries, where you want to sort by one particular field. Add reverse=True to get the largest values first. When two items have the same key, Python keeps them in their original order, which is called a stable sort.

Try It: Sort American Cities

Click Test My Code. Then add another city and sort again. The populations are rounded, approximate figures.

What this code does: It sorts a list of city and population pairs by population, and then sorts the names from the longest to the shortest.
cities = [("Austin", 979000), ("Boston", 654000), ("Denver", 716000), ("Seattle", 749000)]
by_population = sorted(cities, key=lambda c: c[1])
print(by_population)
by_name_length = sorted(cities, key=lambda c: len(c[0]), reverse=True)
print([c[0] for c in by_name_length])

map() and filter() with Lambdas

The built-in map() applies a function to every item of an iterable and returns the transformed values. The built-in filter() keeps only the items for which the function returns True. Both return lazy iterators, so wrap them in list() when you want to see the results.

A lambda is a natural partner for both because the function is usually tiny and used only once. Many Python programmers prefer a list comprehension for the same jobs, as you learned in the Comprehensions lesson. Both styles are correct, so choose the one that is easiest to read in your program.

Try It: Add Sales Tax and Find Cheap Items

Click Test My Code. Then change the tax rate or the price limit.

What this code does: It uses map() to add 8% sales tax to a list of grocery prices, and filter() to keep only the items that cost less than ten dollars.
prices = [4.99, 12.50, 7.25, 19.99, 3.00]
with_tax = list(map(lambda p: round(p * 1.08, 2), prices))
print(with_tax)
cheap = list(filter(lambda p: p < 10, prices))
print(cheap)

max() and min() with Dictionaries

Real programs often store records as dictionaries, such as a player with a name and a score. If you call max() on a list of dictionaries, Python does not know how to compare them. A lambda key solves this by telling Python which value to compare.

The result is the whole dictionary that has the largest or smallest value, not just the number. You can then read any other field from it, such as the player’s name. This pattern is used constantly when working with data from files, websites, and databases.

Try It: Find the Top Scorer

Click Test My Code. Then add another player to the list.

What this code does: It finds the players with the highest and the lowest points in a list of dictionaries and prints their names and scores.
players = [
    {"name": "Liam", "points": 28},
    {"name": "Sophia", "points": 34},
    {"name": "Noah", "points": 21},
]
top = max(players, key=lambda p: p["points"])
low = min(players, key=lambda p: p["points"])
print(top["name"], top["points"])
print(low["name"], low["points"])

Storing Lambdas in a Dictionary

Because a lambda is a value, you can store it in a list or a dictionary and call it later. A dictionary of lambdas works like a small menu of actions, where the key is the name of the action and the value is the function to run. This is often cleaner than a long chain of if and elif statements.

You loop over the dictionary with items() and call each function with the same arguments. Adding a new action is as simple as adding one more line. This idea, called a dispatch table, is used in calculators, command menus, and game controls.

Try It: A Tiny Calculator Menu

Click Test My Code. Then add a "divide" action to the dictionary.

What this code does: It stores three math operations as lambdas in a dictionary and runs each of them with the numbers 12 and 5.
operations = {
    "add": lambda a, b: a + b,
    "subtract": lambda a, b: a - b,
    "multiply": lambda a, b: a * b,
}
for name, func in operations.items():
    print(name, func(12, 5))

Functions That Return Lambdas

A regular function can build and return a lambda. The lambda remembers the variables of the function that created it, which is a closure, as you saw in the scope lesson. This lets you create a family of related functions from one template.

In the example below, one function builds a price calculator for any sales tax rate. Each calculator keeps its own rate, so a Texas calculator and an Oregon calculator never interfere with each other. This technique is the basis of decorators, which you will meet later in the course.

Try It: Sales Tax Calculators for Two States

Click Test My Code. Then create a calculator for your own state’s sales tax rate.

What this code does: It defines a function that returns a lambda for a given tax rate, builds one calculator for Texas and one for Oregon, and prices a $100 item with each.
def make_tax(rate):
    return lambda price: round(price * (1 + rate), 2)
texas = make_tax(0.0825)
oregon = make_tax(0.0)
print(texas(100))
print(oregon(100))

Using Lambdas with input()

Lambdas work well with data typed by the user. You can read a line of numbers, convert them, and then use small lambdas to adjust or filter them. Because input() always returns text, the first step is to split the text and convert each piece into a number.

Here a lambda stored in a variable acts as a reusable rule, and another lambda passed to filter() picks the passing scores. Keeping each rule on one line makes the logic easy to scan. If a rule grows complicated, give it a proper name with def.

Try It: Curve Quiz Scores

The Program Input box is already filled with one line: 92 61 75 98. Click Run Code straight away, then try your own scores separated by spaces.

What this code does: It reads quiz scores, adds a five point curve with a maximum of 100, keeps the curved scores of 70 or more, and prints the highest score.
text = input("Quiz scores: ")
scores = list(map(int, text.split()))
curve = lambda s: min(s + 5, 100)
curved = [curve(s) for s in scores]
passing = list(filter(lambda s: s >= 70, curved))
print("Curved:", curved)
print("Passing:", passing)
print("Highest:", max(curved))
Tip: If you assign a lambda to a name, as in square = lambda n: n * n, you are better off writing a normal def function. Lambdas shine when they are passed directly into another function and never need a name.

Common Mistakes with Lambda Functions

Lambdas are short, which makes small mistakes easy to miss. Most problems come from expecting a lambda to do more than one expression, or from making a lambda too clever to read. When a lambda causes trouble, rewriting it as a normal function usually shows the problem right away.

  • Using statements: lambda x: print(x); return x is a SyntaxError. A lambda holds one expression only.
  • Writing return: lambda x: return x * 2 is a SyntaxError. The value is returned automatically.
  • Forgetting to call it: print(lambda x: x * 2) prints a function object, not a result. Call it with arguments.
  • Late binding in loops: [lambda x: x * n for n in range(3)] makes every lambda use the final value of n. Use a default, as in lambda x, n=n: x * n.
  • Using if without else: lambda x: x if x > 0 is a SyntaxError. A conditional expression needs both parts.
  • Making it too clever: a long lambda with several conditions is hard to read and hard to debug. Use def.
  • Naming a lambda: assigning a lambda to a variable gives no benefit over def and hides the function name in error messages.
  • Expecting map and filter to return lists: they return iterators, so wrap them in list() to see the values.

Good Habits for Writing Lambdas

A good lambda is short enough that its purpose is clear at a glance. Think of it as a small piece of a sentence rather than a paragraph of its own. These habits help you decide when to reach for a lambda and when a regular function is the kinder choice for the next person who reads your code.

  • Use a lambda for short, one-time jobs, especially as a key for sorted(), min(), and max().
  • Use def when the function needs a name, a docstring, several steps, or will be used in many places.
  • Choose a short, meaningful parameter name such as p for price or c for city, and keep the body to one line.
  • Consider a list comprehension instead of map() and filter() when it reads more naturally.
  • Wrap map() and filter() in list() when you need the results more than once.
  • Test a tricky lambda by calling it with sample values before building on it.

Key Takeaways

A lambda is simply a compact way to write a small function. Knowing where it fits, and where it does not, helps you write code that is both short and easy to read. Review the points below before moving on to Python’s built-in functions.

  • A lambda is an anonymous function written as lambda parameters: expression.
  • It returns the value of its single expression automatically.
  • A lambda cannot contain statements, but it can use a conditional expression.
  • The most common uses are the key argument of sorted(), min(), and max(), and the functions map() and filter().
  • Lambdas can be stored in lists and dictionaries and can be returned from other functions.
  • Use def for anything long, reused, or hard to read.

Frequently Asked Questions

Lambda functions raise a few questions again and again, especially about how they differ from normal functions. The answers below give the short version of the rules you practiced in the examples. Open a question to read the answer and rerun the matching example if you want to see it in action.

What is a lambda function in Python?

A lambda function is a small anonymous function written in one line with the syntax lambda parameters: expression. It returns the value of the expression automatically. For example, lambda n: n * n squares a number.

What is the difference between lambda and def?

def creates a named function that can contain many statements, a docstring, and several return statements. A lambda is an unnamed function limited to a single expression. Both create ordinary function objects that you can call, pass around, and return.

Can a lambda have more than one parameter?

Yes. Separate the parameters with commas, as in lambda a, b: a + b. A lambda can also have default values, such as lambda bill, percent=15: bill * percent / 100, and it can accept *args and **kwargs.

Can I use if and else in a lambda?

You cannot use an if statement block, but you can use a conditional expression, such as lambda temp: “Hot” if temp >= 85 else “Comfortable”. Both the if part and the else part are required.

How do I sort a list with a lambda in Python?

Pass the lambda as the key argument, for example sorted(cities, key=lambda c: c[1]). Python calls the lambda on each item and orders the items by the value it returns. Add reverse=True to sort from largest to smallest.

How do map() and filter() work with lambdas?

map(function, iterable) applies the function to every item, and filter(function, iterable) keeps the items for which the function returns True. Both return iterators, so use list() to see the results, as in list(map(lambda p: p * 2, prices)).

When should I not use a lambda?

Avoid a lambda when the logic needs several steps, when the function will be reused in many places, or when it is hard to read. In those cases a regular def function with a clear name and a docstring is easier to understand and to debug.

Why do lambdas in a loop all use the same value?

A lambda looks up variables from the enclosing scope when it is called, not when it is created. In a loop, every lambda sees the final value of the loop variable. Fix it by binding the current value as a default parameter, such as lambda x, n=n: x * n.

Ready for the next step?Explore the most useful functions that Python gives you for free.
Next: Built-in Functions →