Lambdas#

Lambda functions are a concise way to create small, one-off functions in Python. They are defined using the lambda keyword and can have any number of arguments but only one expression.

Lambda functions have the following syntax:

lambda arguments: expression

As a trivial example, a Python function to add two numbers would be written as -

def add(x, y):
  return x + y

As a lambda, this would be written as

1my_add = lambda x,y : x + y

We could then call my_add as a function or pass my_add to yet another function:

1print("Calling directly:", my_add(5,2))
2
3def my_function(x,a,b):
4    print("Passed to my_function:",x(a,b))
5
6my_function(my_add,10,12)
Calling directly: 7
Passed to my_function: 22

Typical Usages#

  • In-Line Function Definition: When a function is so simple that it can be defined in a single line. For example, defining a quick operation like a mathematical formula.

  • Functional Programming: Used extensively with functions like map(), filter(), and reduce() for performing operations on lists or other sequences. For instance, map(lambda x: x*2, numbers) to double each element in a list numbers.

  • Functional Arguments: When passing a simple function as an argument to another function, lambdas provide a concise way to define that function inline. Such examples include -

    • Sorting or Ordering Data: Lambdas are often used in the key argument of sorting functions like sorted() or list.sort(), enabling custom sorting criteria. For example, sorting a list of tuples based on the second element.

    • Data Transformations: In data science and analysis, particularly with libraries like Pandas, lambdas are used for applying quick transformations or calculations to columns in a DataFrame.

    • Event Handlers and Callbacks: In GUI applications or in web frameworks, lambdas are used for defining simple event handlers or callbacks that execute in response to an event, like a button click.

  • Temporary or Auxiliary Functions: When a small utility function is needed temporarily, and there’s no need to define a full function for it. This is common in scripting or automating small tasks.

Limitations#

While lambda functions are usesful for their succinctness and convenience, they do have several limitations:

  • Single Expression: The most significant limitation is that they are restricted to a single expression. This means you cannot have multiple statements or complex logic within a lambda function.

  • Readability: For complex operations, lambdas can reduce readability. Python emphasizes readability, and sometimes a properly named regular function is more understandable and maintainable.

  • No Statements: Lambda functions cannot include statements like return, pass, assert, or annotations. They are purely functional in nature. You cannot have assignment statements in a lambda. This means you cannot set a variable inside a lambda function.

  • Limited Exception Handling: Since you cannot use statements, you can’t handle exceptions within a lambda function using try-except blocks, which can be a significant drawback in error-prone operations.

  • Limited Namespace Access: Lambdas have limited access to variables that are not in their local scope or passed as arguments. While they can access variables in the outer scope, they cannot modify them.

  • Lack of Documentation: Unlike regular functions, lambdas do not support docstrings, so you cannot document a lambda function’s behavior right where it’s defined.

  • No Recursion or Self-Reference: Lambda functions cannot be recursive, i.e., they cannot call themselves, because they have no name to refer to themselves.

Examples#

Here’s several examples of lambda’s in use:

1# Square a number
2square = lambda x: x**2
3print(square(5))
25
1# Filter even numbers
2numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
3even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
4print(even_numbers)
[2, 4, 6, 8, 10]
1# Sort Tuples by the Second Item
2tuples = [(1, 2), (3, 1), (5, 0), (4, 2)]
3sorted_tuples = sorted(tuples, key=lambda x: x[1])
4print(sorted_tuples)
[(5, 0), (3, 1), (1, 2), (4, 2)]
1# Capitalize Names
2names = ['alice', 'bob', 'charlie']
3capitalized_names = list(map(lambda name: name.capitalize(), names))
4print(capitalized_names)  # Output: ['Alice', 'Bob', 'Charlie']
['Alice', 'Bob', 'Charlie']
1# Calculate Compound Interest
2# Compound Intereset = Principal * (1 + Rate/100)^Time
3compound_interest = lambda principal, rate, time: principal * ((1 + rate/100) ** time)
4print(compound_interest(1000, 5, 2))  # Principal: $1000, Rate: 5%, Time: 2 years
1102.5
1# Compute Annualized Return of an Investment
2# Annualized Return = ((Ending Value / Beginning Value) ^ (1 / Years)) - 1
3annualized_return = lambda beginning_value, ending_value, years: ((ending_value / beginning_value) ** (1 / years)) - 1
4print("{:.2f}".format(annualized_return(1000, 2000, 3)))  # Investment doubling over 3 years
0.26