FunctionsIntermediate8 min36 / 63

Lambda Functions

Learn how to write compact, one-line anonymous functions with lambda, and discover exactly when they make your code cleaner — and when they don't.

You already know how to define a function with def. But sometimes you need a tiny, throwaway function — one so small that giving it a name and a whole block of code feels like overkill. That's where lambda functions come in.

A lambda is a way to write a simple function in a single line, right where you need it. Think of it as a sticky note: perfect for a quick job, not meant to hang on the wall forever.

See it in action

Visual walkthrough1 / 6
1

Functions Without a Name

A lambda is a tiny, one-line function you write right where you need it — no def, no name, no ceremony. Think of it as a sticky note instead of a formal memo.

Lambdas don't replace regular functions — they're for quick, throwaway logic.

#The Basic Syntax

The syntax looks a little different from def, but it follows a simple pattern:

lambda parameters: expression

  • `lambda` — the keyword that starts it
  • parameters — the inputs (just like a regular function's arguments)
  • expression — a single calculation or value to return (no return keyword needed)
These two do identical things — the lambda is just more compact.
# A regular function
def double(x):
    return x * 2

# The exact same thing as a lambda
lambda x: x * 2
Think of it like

Lambda as a sticky note

Imagine you need to leave a quick note for someone: "multiply by 2". You wouldn't write a formal memo — you'd scribble it on a sticky note. A lambda is that sticky note. It's a tiny, in-place function for a task you need right now, not something you plan to reuse across your whole program.

#Where Lambdas Actually Shine: sorted()

The most common place you'll see lambdas in real Python code is as the key= argument to sorted(), min(), and max(). These functions let you say how to compare items — and a lambda is a perfect fit because the logic is usually just one expression.

The lambda receives each name and returns its length — sorted() uses that to order the list.
names = ["Alice", "Bob", "Charlie", "Di"]

# Sort by the LENGTH of each name, shortest first
sorted_names = sorted(names, key=lambda name: len(name))
print(sorted_names)
lambda p: p["price"] tells min() what number to compare — without needing a named helper function.
products = [
    {"name": "apple",  "price": 0.99},
    {"name": "banana", "price": 0.49},
    {"name": "cherry", "price": 3.99},
]

# Find the cheapest product
cheapest = min(products, key=lambda p: p["price"])
print(cheapest["name"])

#Lambdas with map() and filter()

map() applies a function to every item in a list. filter() keeps only the items for which a function returns True. Both accept a function as their first argument — lambdas fit naturally here.

map and filter each receive the lambda and apply it across the list.
numbers = [1, 2, 3, 4, 5]

# Square every number
squared = list(map(lambda n: n ** 2, numbers))
print(squared)

# Keep only even numbers
evens = list(filter(lambda n: n % 2 == 0, numbers))
print(evens)
Tip

List comprehensions are often cleaner

Many experienced Python developers prefer list comprehensions over map/filter with lambdas because they read more like plain English:

``python squared = [n ** 2 for n in numbers] evens = [n for n in numbers if n % 2 == 0] ``

Both approaches work — pick whichever feels more readable to you and your team.

#Lambdas with Multiple Parameters

A lambda can accept more than one parameter — just separate them with commas, the same way you would in a def.

Two parameters, one expression. Clean and simple.
add = lambda x, y: x + y
print(add(3, 7))

#The Key Limit: One Expression Only

A lambda can only contain a single expression — it cannot contain statements like if/else blocks, for loops, print() calls, or return. The moment your logic needs more than one step, reach for a regular def instead.

Common mistake

You can't put statements inside a lambda

This will cause a SyntaxError:

``python # WRONG — statements are not allowed lambda x: if x > 0: return x return -x ``

Instead, write a proper function:

``python def absolute_value(x): if x > 0: return x return -x ``

If the logic doesn't fit on one line comfortably, it doesn't belong in a lambda.

#Assigning a Lambda to a Name — Usually a Smell

You can assign a lambda to a variable, like double = lambda x: x * 2. But Python's own style guide (PEP 8) warns against this. If you're giving the function a name anyway, just use def — it's more readable, easier to debug, and plays nicer with tools.

When you need a named function, def is the right tool.
# Technically works, but discouraged
double = lambda x: x * 2

# Preferred — clearer and just as short
def double(x):
    return x * 2
Watch out

Named lambdas are harder to debug

When a named lambda raises an error, the traceback shows <lambda> instead of the function's name — which makes debugging much harder. A def function always shows its actual name in tracebacks, making problems easier to find.

#When to Use Lambda vs. def

Here's a simple rule of thumb:

  • Use `lambda` when you need a short, one-expression function inline — especially as a key= argument or with map/filter.
  • Use `def` when the logic has multiple steps, when you'll reuse the function, or when giving it a name makes your intent clearer.

Readability always wins.

Quick check

Which of the following is a valid use of a lambda function?

Key takeaways

  • A lambda is a one-line anonymous function: `lambda params: expression`.
  • They shine as `key=` arguments in `sorted()`, `min()`, and `max()`.
  • Lambdas only support a single expression — no loops, assignments, or multi-line logic.
  • Assigning a lambda to a name is usually a sign you should use `def` instead.
  • When in doubt, choose `def` — it's easier to read, test, and debug.
Practice challenges
Test yourself · earn XP
0/4
Predict the output#1

What does this code print?

predict-output
numbers = [3, 1, 4, 1, 5]
sorted_nums = sorted(numbers, key=lambda n: -n)
print(sorted_nums)
Fix the bug#2

This code is supposed to keep only the words longer than 3 characters, but it has a bug. What is wrong?

fix-bug
words = ["hi", "hello", "cat", "world"]
long_words = list(filter(lambda w: return len(w) > 3, words))
print(long_words)
Fill in the blank#3

Complete the lambda so that sorted() orders the names from shortest to longest.

names = ["Charlie", "Bo", "Alice", "Di"]
result = sorted(names, key=lambda name: (name))
print(result)
Reorder the lines#4

Put these lines in the right order to square every number in the list and print the result.

1
squared = list(map(lambda n: n ** 2, numbers))
2
print(squared)
3
numbers = [1, 2, 3, 4]
Your turn
Practice exercise

You have a list of student records, each a dictionary with a "name" and a "score". Use sorted() with a lambda to sort the students by score from highest to lowest. Then use filter() with a lambda to create a list of only the students who passed (score >= 60). Print both results.

Try it live — edit the code and hit Run to execute real Python:

solution.py · editable