Lambda functions

A lambda function is a small, anonymous function that can be defined in a single line. It is also known as an "anonymous function" because it doesn't have a name like regular functions.

Lambda functions are typically used when you need a simple function for a short period of time and don't want to define a separate function using the def keyword. They are commonly used in combination with built-in functions like sorted().

The basic syntax of a lambda function consists of the lambda keyword, followed by the arguments (separated by commas), a colon :, and the expression that defines the function's behavior. Here's an example:

multiply = lambda x, y: x * y

In this example, we define a lambda function called multiply that takes two arguments x and y and returns their product. The expression x * y defines the behavior of the function.

Lambda functions are often used as one-liners, where they are defined and used in the same line. Here's an example using the built-in sorted() function:

fruits = ['strawberry', 'fig', 'apple', 'cherry', 'banana']
sorted_fruits = sorted(fruits, key=lambda fruit: len(fruit))

In this code, we use a lambda function to sort the fruits list by the length of each fruit name. The sorted() function takes the list fruits and sorts it based on the criteria defined by the lambda function, which in this case is the length of each fruit name. The result is stored in sorted_fruits.

Lambda functions are particularly useful when you need to define a simple function for a one-time use. However, they have some limitations. Lambda functions can only contain a single expression, and they cannot include statements or multiple lines of code.

It's important to note that while lambda functions can be convenient, it's also important to write code that is clear and easy to understand. For more complex operations or functions with multiple lines of code, it's generally better to use regular functions defined with the def keyword.