Python : Lambda

In Python, a lambda function is a small, anonymous function defined using the lambda keyword. Lambda functions can take any number of arguments, but they can only have one expression. They are particularly useful for short, simple operations that can be expressed in a single line of code. Here's a basic overview of lambda functions:

Syntax:


The syntax for a lambda function is as follows:

lambda arguments: expression


 Example:


Here's an example of a lambda function that adds two numbers together:

add = lambda x, y: x + y
print(add(3, 5))  # Output: 8

 

Using Lambda with Built-in Functions:


Lambda functions are often used with built-in functions like map(), filter(), and sorted() to apply simple operations to elements in an iterable or to filter elements based on a condition.

Example with map() :

numbers = [1, 2, 3, 4, 5]
squared_numbers = list(map(lambda x: x ** 2, numbers))
print(squared_numbers)  # Output: [1, 4, 9, 16, 25]

 

Example with filter():

numbers = [1, 2, 3, 4, 5]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers)  # Output: [2, 4]

 

Example with sorted():

names = ['Alice', 'Bob', 'Charlie', 'David', 'Eve']
sorted_names = sorted(names, key=lambda x: len(x))
print(sorted_names)  # Output: ['Bob', 'Alice', 'David', 'Eve', 'Charlie']

 

Limitations of Lambda Functions:


While lambda functions are convenient for simple operations, they have limitations compared to regular functions defined with def :

  • They can only contain a single expression.
  • They are less readable than regular functions for complex operations.
  • They can't have docstrings.
  • They can't include statements like return, pass, assert, etc.

Lambda functions are most commonly used in situations where a small, anonymous function is needed for a short period of time, such as when passing a function as an argument to another function or when working with built-in functions that accept function arguments. If the operation becomes more complex or requires additional functionality, it's usually better to use a regular named function defined with def.