Skip to Content
Course content

4.4.1 Anonymous functions and their applications

Anonymous functions are functions that are defined without a name. In Python, the most common way to create an anonymous function is by using the lambda keyword. These functions are typically short and are often used as arguments to higher-order functions, where defining a full, named function might seem unnecessary.

What Are Anonymous Functions?

An anonymous function is a function that doesn’t have a name, and it is usually created in a single line of code. In Python, these functions are defined using the lambda keyword.

The syntax for an anonymous function is:

lambda arguments: expression
  • lambda: This keyword is used to create the function.
  • arguments: These are the inputs to the function.
  • expression: This is the single expression that the function evaluates and returns.

For example, the following defines a simple anonymous function that adds two numbers:

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

Here, the function lambda x, y: x + y is an anonymous function because it doesn’t have a name like a regular function defined with def. Instead, it is assigned to the variable add.

Applications of Anonymous Functions

Anonymous functions are often used in situations where a simple function is required for a short period of time. They are frequently passed as arguments to higher-order functions like map(), filter(), and sorted(). Below are some common use cases for anonymous functions:

1. Using Anonymous Functions with map()

The map() function applies a given function to all items in an iterable (e.g., a list) and returns an iterator that produces the results.

Example:

numbers = [1, 2, 3, 4]
doubled = list(map(lambda x: x * 2, numbers))
print(doubled)  # Output: [2, 4, 6, 8]

In this case, the lambda function lambda x: x * 2 is applied to each element of the list numbers. The result is a new list where each element is doubled.

2. Using Anonymous Functions with filter()

The filter() function filters the elements of an iterable based on a function. The function should return True or False for each element, and filter() will include only those elements that evaluate to True.

Example:

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

Here, the lambda x: x % 2 == 0 function is used to filter out even numbers from the list. Only the elements that return True for this condition are included in the result.

3. Using Anonymous Functions with sorted()

The sorted() function sorts an iterable based on a function that extracts a sorting key. Lambda functions are often used for this purpose.

Example:

students = [
    {'name': 'Alice', 'age': 22},
    {'name': 'Bob', 'age': 25},
    {'name': 'Charlie', 'age': 20}
]

# Sorting students by age using lambda
sorted_students = sorted(students, key=lambda x: x['age'])
print(sorted_students)

Output:

[
    {'name': 'Charlie', 'age': 20},
    {'name': 'Alice', 'age': 22},
    {'name': 'Bob', 'age': 25}
]

Here, the lambda function lambda x: x['age'] is used to sort the list of dictionaries by the age key.

4. Using Anonymous Functions with reduce()

The reduce() function (from the functools module) applies a binary function (a function with two arguments) to the elements of an iterable and reduces them to a single cumulative result.

Example:

from functools import reduce

numbers = [1, 2, 3, 4]

# Finding the product of all numbers using reduce and lambda
product = reduce(lambda x, y: x * y, numbers)
print(product)  # Output: 24

In this case, the lambda function lambda x, y: x * y is used to multiply all the numbers together.

5. Inserting Anonymous Functions in Data Structures

In some cases, anonymous functions can be stored in data structures like lists or dictionaries for dynamic use.

Example:

# Storing lambda functions in a dictionary
functions = {
    'add': lambda x, y: x + y,
    'subtract': lambda x, y: x - y,
    'multiply': lambda x, y: x * y
}

result_add = functions['add'](5, 3)        # Output: 8
result_subtract = functions['subtract'](5, 3)  # Output: 2
result_multiply = functions['multiply'](5, 3)  # Output: 15
print(result_add, result_subtract, result_multiply)

Here, the lambda functions are stored in a dictionary and can be called dynamically by referencing their keys.

Advantages of Anonymous Functions

  • Concise and Simple: Lambda functions allow you to write short, simple functions in a single line of code, reducing the need for full function definitions.
  • Functional Programming: They align well with functional programming techniques, where functions are passed as arguments and returned from other functions.
  • Temporary Use: Ideal for cases where the function is required only temporarily or for a short duration, avoiding the need to define a function elsewhere in the code.

Limitations of Anonymous Functions

  • Single Expression: Lambda functions can only have one expression. This means they can't contain multiple statements or perform complex logic.
  • Readability: Overusing lambda functions or using them for complex operations can reduce code readability and clarity, especially for people unfamiliar with lambda functions.
  • Limited Functionality: Due to their single-expression nature, lambda functions are limited in what they can do. If the function requires more complex logic, it’s better to define a full function using def.

Conclusion

  • Anonymous functions are a powerful feature of Python, enabling concise and temporary functions to be created inline.
  • They are most commonly used in conjunction with higher-order functions like map(), filter(), and sorted().
  • While they are concise and flexible, lambda functions should be used judiciously, as overuse can make code harder to read and maintain.

Commenting is not enabled on this course.