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:

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:

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:

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:

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?

Python

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

Let's see an example:

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?

Python

What will be the output?

Python

What will be the output?

Python