Start Coding

Topics

Python Lambda Functions

Lambda functions in Python are small, anonymous functions that can have any number of arguments but can only have one expression. They are also known as lambda expressions or anonymous functions.

Syntax and Usage

The basic syntax of a lambda function is:

lambda arguments: expression

Lambda functions are typically used for short, simple operations where a full function definition would be verbose or unnecessary.

Key Features

  • Can be used wherever function objects are required
  • Limited to a single expression
  • More concise than regular function definitions
  • Often used with higher-order functions like map(), filter(), and reduce()

Examples

1. Simple Lambda Function


# Lambda function to square a number
square = lambda x: x ** 2

print(square(5))  # Output: 25
    

In this example, we define a lambda function that squares its input. It's equivalent to:


def square(x):
    return x ** 2
    

2. Lambda with Multiple Arguments


# Lambda function to add two numbers
add = lambda x, y: x + y

print(add(3, 4))  # Output: 7
    

Common Use Cases

Lambda functions are particularly useful in scenarios where you need a simple function for a short period. They're commonly used with built-in functions like sorted(), map(), and filter().

Sorting a List of Tuples


pairs = [(1, 'one'), (3, 'three'), (2, 'two'), (4, 'four')]
sorted_pairs = sorted(pairs, key=lambda pair: pair[1])

print(sorted_pairs)
# Output: [(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')]
    

In this example, we use a lambda function as the key for sorting, based on the second element of each tuple.

Best Practices

  • Use lambda functions for simple operations
  • For complex logic, prefer regular Python Functions
  • Combine with List Comprehensions for more readable code
  • Be cautious with readability; sometimes a named function is clearer

Limitations

While lambda functions are powerful, they have some limitations:

  • Cannot contain multiple expressions
  • Cannot include statements (e.g., return, assert, or raise)
  • Limited to a single line of code

For more complex operations, consider using regular Python Functions instead.

Conclusion

Lambda functions in Python offer a concise way to create small, anonymous functions. They're particularly useful for simple operations and when working with higher-order functions. While they have limitations, understanding and using lambda functions can lead to more elegant and efficient code in appropriate situations.