Python Lambda Functions

Last Updated 13 Sep, 2026

A lambda function is a small anonymous function in Python. It is useful when you need a simple function for a short operation without defining it using def.

What is a Lambda Function?

A lambda function is a function without a name. It can take any number of arguments but contains only one expression.

For example:

square = lambda x: x * x

print(square(5))

Output:

25

Here, lambda x: x * x creates a function that takes x and returns its square.

Lambda functions are generally useful when a simple operation is needed for a short period, especially with functions such as map(), filter(), and sorted().

Lambda Syntax

The basic syntax of a lambda function is:

lambda arguments: expression

For example:

double = lambda x: x * 2

print(double(6))

Output:

12

The same operation using a normal function would be:

def double(x):
    return x * 2

A lambda function is usually written when the operation is simple enough to fit into a single expression.

Lambda with Arguments

A lambda function can accept one or more arguments.

With one argument:

cube = lambda x: x ** 3

print(cube(3))

Output:

27

With multiple arguments:

add = lambda a, b: a + b

print(add(10, 20))

Output:

30

Another example:

multiply = lambda a, b, c: a * b * c

print(multiply(2, 3, 4))

Output:

24

A lambda can also be used directly without assigning it to a variable:

print((lambda a, b: a + b)(5, 10))

Output:

15

Lambda with map(), filter(), and sorted()

Lambda functions are commonly used with Python's built-in functions such as map(), filter(), and sorted().

Lambda with map()

The map() function applies a function to every item in an iterable.

For example, you can use a lambda function to double every number in a list:

numbers = [1, 2, 3, 4, 5]

result = map(lambda x: x * 2, numbers)

print(list(result))

Output:

[2, 4, 6, 8, 10]

Here, the lambda function is applied to each element of numbers.

Lambda with filter()

The filter() function selects elements that satisfy a condition.

For example, to get even numbers:

numbers = [1, 2, 3, 4, 5, 6]

result = filter(lambda x: x % 2 == 0, numbers)

print(list(result))

Output:

[2, 4, 6]

The lambda expression returns True for even numbers, so filter() keeps those elements.

Lambda with sorted()

The sorted() function can use a lambda function through its key parameter to determine how items should be sorted.

For example, sorting a list of words by their length:

words = ["Python", "AI", "Django", "Code"]

result = sorted(words, key=lambda word: len(word))

print(result)

Output:

['AI', 'Code', 'Python', 'Django']

The lambda function lambda word: len(word) tells sorted() to use the length of each word as the sorting key.

Lambda functions are most useful for short, simple operations. When the logic becomes complex or needs to be reused in several places, a regular function defined with def is usually clearer.