Lambda Expressions

What are Lambda Expressions?

Lambda expressions in Python provide a convenient way to create anonymous functions. These are functions that are not bound to a name at runtime. Traditionally, a function in Python is defined using the def keyword, and it should have a name to be referred to. However, there might be occasions where you need a quick, one-time function that you don’t want to define in a full-fledged manner. This is where lambda functions come in handy.

1adder = lambda x, y: x + y
2print(adder(5, 3))

In the example above, we have a lambda function that takes two parameters (x and y) and returns the sum of both. We can use this function multiple times in our program, all without giving it an official name through a def statement. This can help to minimize repetition and make our code more concise.

Structure of Lambda Functions

Lambda functions in Python have the following syntax:

1lambda arguments: expression

The arguments are the input to our function. These are what we will be working with inside our expression. The expression is what our function is going to return. It’s important to note that lambda functions can have any number of arguments but only one returned expression.

For instance, a lambda function that squares a number would look like:

1square = lambda x: x ** 2
2print(square(4))

The lambda function above takes in a single argument x and returns the square of that argument.

Note

Lambda functions can be used wherever function objects are required. They are syntactically restricted to a single expression. Like def defined functions, Lambda functions also have their own local namespace and cannot access variables other than those in their parameter list and those in the global namespace.

Advantages of Lambda Expressions

There are several advantages to using lambda expressions:

  1. They’re compact: Lambda expressions allow you to declare small anonymous functions in places where you don’t want to use the bulky syntax of a regular function.

  2. They’re inline: Lambda expressions declare a function on the spot. This is useful in cases where you need a small function for a short period of time, and you don’t want to have to declare it elsewhere.

  3. They have no side effects: Since lambda expressions don’t have a name or a defined scope, they can’t interfere with anything outside their scope. This makes them safe to use in any context.

To fully harness the power of lambda expressions in Python, it’s important to understand when it’s best to use them and when to use traditional function definitions.