Lambda functions

Lambda functions, also known as anonymous functions or lambda expressions, are a way to create small, unnamed functions in Python. They are typically used for simple operations and can be defined in a single line of code. Lambda functions are especially useful when you need a function for a short-term or specific purpose, without having to define a full named function. Here's an introduction to lambda functions and their use:

The syntax of a lambda function is as follows:

lambda arguments: expression
  • lambda: Keyword used to define a lambda function.
  • arguments: Input parameters of the function.
  • expression: A single expression that the function will evaluate and return.

Suppose you need a quick function to calculate the square of a number. Instead of defining a named function, you can use a lambda function:

square = lambda x: x**2
result = square(5)  # Call the lambda function with an argument
print(result)  # Output: 25

In this example, the lambda function "lambda x: x**2" calculates the square of the input "x". The function is assigned to the variable "square", and you can call it like a regular function.

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

  • map() applies a function to each element of an iterable.
  • filter() filters elements of an iterable based on a function's output.
  • sorted() sorts elements of an iterable using a custom sorting key.

Here's an example using map() with a lambda function:

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

In this example, the map() function applies the lambda function to each element of the numbers list, resulting in a new list of squared numbers.

While lambda functions are concise and useful for simple operations, they are not meant for complex logic or multi-line functions. In such cases, it's better to use regular named functions for improved readability and maintainability.

Lambda functions provide a convenient way to create small, throwaway functions without the need for a full function definition. They are particularly valuable when you need a function quickly for a specific task, especially in combination with built-in functions or in functional programming paradigms.