Q1. What is a lambda function in Python?
A lambda function is a small anonymous function defined with the lambda keyword. It can have any number of arguments but only one expression. Example:
add = lambda x, y: x + y
print(add(3, 5)) # 8 Lambdas are often used as short, throwaway functions.Q2. When would you use a lambda function?
Lambda functions are useful when you need a simple function for a short period, especially as arguments to higher-order functions like map(), filter(), sorted(), etc. They are more concise than defining a full function with def.
Q3. How do you use lambda with map() and filter()?
map() applies a function to all items in an iterable. filter() selects items based on a condition. Example:
numbers = [1,2,3,4]
squared = list(map(lambda x: x**2, numbers))
evens = list(filter(lambda x: x % 2 == 0, numbers))Q4. What are the limitations of lambda functions?
Lambda functions can only contain a single expression, not statements (like print or assignments). They lack annotations and cannot have multiple lines. They are limited to simple operations. For complex logic, define a regular function.
Q5. Can lambda functions be assigned to variables?
Yes, you can assign a lambda to a variable, but it's often discouraged because it defeats the purpose of anonymous functions. Regular def statements are clearer for named functions. Use lambdas mainly when they are used directly as arguments.
