Python – Lambda Functions

In Python, a lambda function is a small anonymous function that can have any number of arguments but can only have one expression. It is created using the lambda keyword, followed by a comma-separated list of arguments, a colon, and an expression. Here is the general syntax of a lambda function:

lambda arguments: expression

Lambda functions are often used as a way to create small, one-line functions that can be passed as arguments to other functions. They are particularly useful when you need to create a function on the fly without defining a named function.

Here’s an example of a lambda function that squares a number:

square = lambda x: x ** 2

You can then call the lambda function like a regular function:

result = square(5)
print(result) # Output: 25

Lambda functions can also be used as arguments for other functions. For example, the map() function takes a function and an iterable as arguments and applies the function to each element of the iterable. Here’s an example of using a lambda function with map() to square each element of a list:

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

Lambda functions are a powerful tool in Python for creating small, anonymous functions that can be used in a variety of contexts. However, they should be used judiciously, as they can make code harder to read and understand if overused.