What is a lambda function in Python?
a) A function defined with the lambda keyword
b) A function that takes multiple arguments
c) A function that returns None
d) A function that can only be used once
Answer:
a) A function defined with the lambda keyword
Explanation:
A lambda function in Python is a small, anonymous function defined with the lambda
keyword. Lambda functions can have any number of arguments but only one expression, which is evaluated and returned. They are often used for short, simple operations that are needed temporarily in the code.
double = lambda x: x * 2
print(double(5)) # Output: 10
In this example, a lambda function is defined to double the input value. Lambda functions are typically used in scenarios where a small function is needed for a short period, such as in list comprehensions, map, filter, or as an argument to higher-order functions.
While lambda functions are concise, they should be used judiciously. For more complex operations, it’s usually better to define a full function using the def
keyword.