Functions III

Introduction to lambda functions

This tutorial explores lambda functions in Python, covering their syntax, usage, and advantages over traditional function definitions.


Let's start with a simple function that adds two numbers:

def add_numbers(a, b): return a + b
Python

That's the classical way of creating a function in Python.

However, Python provides another, more concise way to create functions using lambda functions.

A lambda function is an anonymous function expressed as a single statement.

The syntax of a lambda function is as follows:

lambda arguments: expression
Python

There's the lambda keyword followed by a list of arguments, a colon, and then the expression that the function will evaluate and return.

The add_numbers function above can be expressed using a lambda function:

lambda x, y: x + y
Python

You can see that lambda functions can be much more concise than defining a full function using the def keyword.

You can assign a lambda function to a variable, just like a regular function:

add = lambda x, y: x + y result = add(5, 3) print(result)
Python
Output

In this example, we assigned the lambda function to the variable add and then called it with arguments 5 and 3.


What will be the output?

multiply = lambda x, y: x * y result = multiply(4, 5) print(result)
Python

Just like regular functions, lambda function can use variables that are defined outside their local scope.

Let's see an example:

x = 10 add_x = lambda y: x + y result = add_x(5) print(result)
Python
Output

In this example, the lambda function add_x takes one argument y and adds it to the variable x, which is defined outside the lambda function.


What will be the output?

x = 5 add_x = lambda y: x + y result = add_x(5) print(result)
Python

What will be the output?

x = 5 add_x = lambda y: x + y x = 10 result = add_x(5) print(result)
Python

What will be the output?

double = lambda x: x * 2 result = double(10) print(result)
Python