Believemy logo purple

Anonymous functions with Python (lambda)

In Python, the lambda keyword is used to define anonymous (i.e. unnamed) functions. We call them lambda functions.
Believemy logo

In Python, the lambda keyword lets you create what are called anonymous functions.

These are functions without an explicit name, often used for small, one-off operations such as:

  • sorting;
  • transforming;
  • or filtering data.

The main appeal of lambda functions lies in their conciseness (you can write them quickly 😉) and their contextual use (they’re handy). That’s why they are frequently used inside other functions or passed as arguments to higher-order functions such as map(), filter() or sorted().

 

Syntax of an anonymous (lambda) function

The syntax of a lambda function is one of its greatest strengths. It is minimalist, simple and straightforward:

PYTHON
lambda arguments: expression

Let’s break this down:

  • lambda: the keyword used to define an anonymous function;
  • arguments: one or more parameters passed to the function;
  • expression: a single line of code that is evaluated and returned automatically.

Keep this in mind: the result is returned automatically, so you don’t need the return keyword.

A quick example to illustrate the syntax:

PYTHON
addition = lambda x, y: x + y
print(addition(3, 5))  # Result: 8

Here, a variable named addition holds a lambda function (lambda).

It takes two arguments (x, y) and returns the result after the colon (:)—namely x + y.

When we display the result of this lambda function with print(), we indeed get 8.

 

Key characteristics of lambda functions

Lambda functions have several distinct characteristics that make them unique in the Python ecosystem:

  • Nameless (anonymous): they’re generally used for quick statements;
  • Concise: their syntax (see above) reduces the need to write full blocks for simple tasks;
  • Single expression only: you can’t include multiple statements or loops 😋;
  • No documentation: you can’t add a docstring.

In short, use lambda when it provides an immediate simplification of the code.

Prefer regular functions with def if the logic becomes too complex or if the function needs to be reused.

 

Differences between lambda and def

Different purposes

Both lambda and def let you create functions in Python, but they serve very different purposes:

  • lambda is a short, inline syntax (no line break) reserved for single expressions—simple, basic instructions;
  • def lets you define multi-line functions with conditions, loops and complex blocks.

 

Different syntaxes

Here’s an example highlighting the difference between a lambda function and a regular function with def:

PYTHON
# With lambda
add = lambda x, y: x + y

# With def
def add(x, y):
    return x + y

A lambda function fits on one line for a simple instruction, whereas a traditional function usually needs at least two lines.

 

When to use lambda vs. def?

Use caseUse lambda?Use def?
Single-line simple function✅ Yes❌ No
Function reused many times❌ No✅ Yes
Need a docstring or type hints❌ No✅ Yes
Need multiple statements❌ No✅ Yes

 

Examples of using lambda functions

Lambda functions are widely used when they are passed as arguments to functions such as map(), filter(), reduce() or sorted().

Using a lambda with map()

PYTHON
numbers = [1, 2, 3]
double = list(map(lambda x: x * 2, numbers))
print(double)  # [2, 4, 6]

 

Using a lambda with filter()

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

 

Using a lambda with reduce()

PYTHON
from functools import reduce

numbers = [1, 2, 3, 4]
product = reduce(lambda x, y: x * y, numbers)
print(product)  # 24

Remember to import reduce from functools.

 

Using a lambda with sorted()

PYTHON
names = ['Python', 'AI', 'Lambda', 'Code']
sorted_names = sorted(names, key=lambda x: len(x))
print(sorted_names)  # ['AI', 'Code', 'Lambda', 'Python']

Another example with dictionaries:

PYTHON
people = [
  {"name": "Alice", "age": 25},
  {"name": "Bob", "age": 20},
  {"name": "Charlie", "age": 30}
]

sorted_people = sorted(people, key=lambda x: x["age"])
print(sorted_people)

# ["Bob", "Alice", "Charlie"]

 

Using lambda with pandas

The Pandas library is essential for data manipulation in Python.

A common use of lambda is with Pandas’ apply() method, which applies a transformation to rows or columns of a DataFrame.

Example 1: Format a column in uppercase

PYTHON
import pandas as pd

df = pd.DataFrame({
    'name': ['John', 'Elton', 'Magla']
})

df['name_upper'] = df['name'].apply(lambda x: x.upper())

print(df)

Result:

 namename_upper
0JohnJOHN
1EltonELTON
2MaglaMAGLA

 

Example 2: Row-by-row weighted calculation

PYTHON
df = pd.DataFrame({
    'value': [1, 2, 3],
    'weight': [3, 4, 5]
})

df['weighted'] = df.apply(lambda row: row['value'] * row['weight'], axis=1)

print(df)

Result:

 valueweightweighted
0133
1248
23515

Always set axis=1 in apply() if you want to work on rows. Otherwise, Pandas applies the function column by column (axis=0) by default.

 

Example 3: Create a conditional column

PYTHON
df = pd.DataFrame({
    'score': [75, 42, 90, 60]
})

df['grade'] = df['score'].apply(lambda x: 'Pass' if x >= 60 else 'Fail')

print(df)

Result:

 scoregrade
075Pass
142Fail
290Pass
360Pass

This kind of operation is very common in data analysis to create segments, scores or labels from numeric or text-based criteria.

 

Frequently asked questions about lambda functions in Python

Can you write multiple lines in a lambda?

No. A lambda function is limited to one single expression. It can’t contain multiple statements, loops or classic if/else blocks. For complex processing, use def.

 

How can I learn Python?

It’s important to choose a course that is fully up to date, like the one we offer.

 

Is it possible to give a name to a lambda function?

Technically yes, but it’s not recommended. If you need to name a lambda, it’s better to use def, in line with PEP 8.

PYTHON
# ❌ Bad practice
f = lambda x: x + 1

# ✅ Good practice
def f(x):
    return x + 1

 

Can you add type annotations to a lambda?

No. Lambdas don’t support type annotations like regular functions. To properly type-annotate a function, you must use def.

Discover our python glossary

Browse the terms and definitions most commonly used in development with Python.