Python Lamda Functions

Lambda functions in Python are small anonymous functions defined using the lambda keyword. They are typically used for short, simple functions that you might want to declare inline, such as when using functions like map(), filter(), or sort(), or when you need a small function for a short period of use.

Syntax

The basic syntax of a lambda function is:

lambda arguments: expression

This creates a function that takes arguments and returns the value of expression. Lambda functions can have any number of arguments but only one expression.

Characteristics

  • Anonymous: Lambda functions are often called anonymous because they are not declared in the standard manner by using the def keyword. You don’t need to give them a name at the time of creation.
  • Single Expression: They are limited to a single expression. This means a lambda function can’t have multiple expressions or statements like a regular function.
  • Versatile Use: They can be used wherever function objects are required, such as in callbacks, or as part of functional programming constructs.

Examples

Example 1: Adding Two Numbers

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

This lambda function takes two arguments, x and y, and returns their sum.

Example 2: Sorting a List of Tuples

Consider you have a list of tuples where each tuple contains a name and age. You want to sort this list by age:

people = [('Alice', 25), ('Bob', 30), ('Cathy', 20)]
people.sort(key=lambda person: person[1])
print(people)  # Output: [('Cathy', 20), ('Alice', 25), ('Bob', 30)]

Here, the lambda function helps define the key for sorting, which is the age (the second element of each tuple).

Example 3: Filtering a List

Suppose you want to filter a list to include only even numbers:

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

The lambda function here specifies the condition used by filter() to decide which elements to keep.

When to Use Lambda Functions

Lambda functions are particularly useful when you need a simple function for a short period and where defining a full function using def would be unnecessarily verbose. They are often used in conjunction with functions that take other functions as arguments. However, if the function is complex or requires multiple expressions, it’s usually better to define it more clearly using the standard function definition method with def.