python-funciones-lambda

Lambda Functions in Python

  • 3 min

Lambda functions, also known as anonymous functions, are an alternative and concise way to define functions. As their name suggests (unlike regular functions) lambda functions do not have a name.

Generally, they are small functions and are used in contexts where a function is needed temporarily (for example, when used as parameters for other functions).

If you want to learn more, check out the Introduction to Programming Course

Lambda functions

In Python, Lambda functions are defined using the keyword lambda followed by a parameter list, followed by a colon (:) and an expression.

lambda parameters: expression
Copied!

For example, we can define a lambda function that calculates the square of a number as follows:

square = lambda x: x * x
Copied!

This lambda function

  • Takes one argument x
  • Returns the result of x * x.

Lambda functions with multiple arguments

In this example, sum is a lambda function that takes two arguments x and y and returns their sum.

# Syntax: lambda arguments: expression
sum = lambda x, y: x + y
print(sum(3, 5))  # Output: 8
Copied!

Practical examples

Let’s see some examples of how lambda function syntax is used in Python:

Lambda functions vs defined functions

Lambda functions are useful when we need a quick function to perform a simple operation. They are often used in combination with higher-order functions, such as map(), filter(), and reduce().

  • Syntax limitations: Lambda functions are limited to a single expression and cannot contain multiple statements or lines of code.
  • Readability: Lambda functions can affect code readability if overused or used in complicated situations.
  • Debugging: It can be more difficult to debug lambda functions compared to functions with explicit names.

In summary, they are very useful for what they are, but don’t use them recklessly either 😉