Python Documentation

Lambda Functions

Lambda Functions in Python

Lambda functions, also known as anonymous functions, are small, one-time use functions that don't require a formal def statement. They are useful for short operations that are not going to be reused.

Basic Syntax

The basic syntax of a lambda function is:

lambda arguments: expression

Simple Example

Let's create a lambda function that adds 10 to a given number:

add_ten = lambda x: x + 10
print(add_ten(5)) # Output: 15

Lambda with Multiple Arguments

Lambda functions can take multiple arguments:

multiply = lambda x, y: x * y
print(multiply(3, 4)) # Output: 12

Lambda with Built-in Functions

Lambda functions are often used with built-in functions like map(), filter(), and reduce():

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

# Using lambda with filter()
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers) # Output: [2, 4, 6, 8, 10]

Lambda in Sorting

Lambda functions are often used as key functions in sorting operations:

pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]
pairs.sort(key=lambda pair: pair[1])
print(pairs) # Output: [(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')]

Limitations of Lambda Functions

While lambda functions are convenient, they have some limitations:

  • They are restricted to a single expression
  • They cannot contain statements or annotations
  • They are harder to read for complex operations

When to Use Lambda Functions

Lambda functions are best used in situations where:

  • You need a simple function for a short period of time
  • You want to create a function to be used right away (like in sorting or filtering)
  • You need to pass a simple function as an argument to another function

While lambda functions can make code more concise, it's important to balance brevity with readability. For more complex operations, it's often better to use a regular defined function.