Python Lambda Functions: Syntax and Examples

Learn about lambda functions in Python, which are small, anonymous functions defined using the lambda keyword. Discover the syntax and see how lambda functions can take multiple arguments and return a single expression as a result. Explore practical examples, including how to add values using lambda functions.



Python Lambda Functions

A lambda function in Python is a small, anonymous function defined using the lambda keyword. It can take any number of arguments but only has a single expression.

Syntax

lambda arguments: expression

The expression is evaluated and returned as the result.

Example 1: Add 10 to the argument a

Example

x = lambda a: a + 10
print(x(15))
Output

25

Example 2: Multiply arguments a and b

Example

x = lambda a, b: a * b
print(x(7, 8))
Output

56

Example 3: Sum arguments a, b, and c

Example

x = lambda a, b, c: a + b + c
print(x(3, 4, 5))
Output

12

Why Use Lambda Functions?

Lambda functions are particularly useful when used as anonymous functions inside other functions. For instance, you might have a function that multiplies its argument by an unknown number:

Example

def myfunc(n):
    return lambda a: a * n

# Function to double the input
mydoubler = myfunc(2)
print(mydoubler(10))
Output

20

You can also create a function that triples the input:

Example

def myfunc(n):
    return lambda a: a * n

# Function to triple the input
mytripler = myfunc(3)
print(mytripler(10))
Output

30

Combining both in a single program:

Example

def myfunc(n):
    return lambda a: a * n

mydoubler = myfunc(2)
mytripler = myfunc(3)

print(mydoubler(10))
print(mytripler(10))
Output

20
30