What is a lambda function in Python?
A lambda function is an anonymous function defined with the `lambda` keyword. It can take any number of arguments but can only have one expression.
Lambda functions in Python are a concise way to define anonymous functions, which are functions that do not have a name. You can create a lambda function using the lambda
keyword followed by a list of parameters, a colon, and a single expression. The syntax is:
lambda arguments: expression
For example, you can define a simple lambda function that adds two numbers:
add = lambda x, y: x + y
print(add(2, 3)) # Output: 5
Lambda functions are often used in higher-order functions, such as map()
, filter()
, and sorted()
, where you need a simple function for a short duration. For instance, using map()
to double each number in a list:
numbers = [1, 2, 3, 4]
doubled = list(map(lambda x: x * 2, numbers))
print(doubled) # Output: [2, 4, 6, 8]
While lambda functions can make your code more concise, they should be used judiciously, as complex expressions can reduce readability. For more complex functionality, defining a regular function using def
is recommended.