A lambda function in Python is a small anonymous function defined using the lambda keyword. It can have any number of arguments but only one expression, and that expression is automatically returned.
map(), filter(), and sorted().def).The basic syntax of a lambda function is:
lambda arguments: expression
# Basic lambda function syntax
This creates an anonymous function object. For example, lambda x: x * 2 represents a function that doubles its argument.
You can assign a lambda to a variable (giving it a name), or pass it directly into higher-order functions like map(), filter(), and sorted().
Lambda functions can be used wherever functions are required.
# Example 1: Lambda to add two numbers
add = lambda a, b: a + b
print(add(5, 3)) # 8
# Example 2: Lambda with map
numbers = [1, 2, 3, 4]
squared = list(map(lambda x: x**2, numbers))
print(squared) # [1, 4, 9, 16]
# Example 3: Lambda with filter
numbers = [1, 2, 3, 4]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers) # [2, 4]
add(5, 3) uses a lambda to add two numbers and prints 8.map(lambda x: x**2, numbers) applies the lambda to every element in [1, 2, 3, 4], producing [1, 4, 9, 16].filter(lambda x: x % 2 == 0, numbers) keeps only numbers divisible by 2, giving [2, 4].In all these cases, the lambda replaces a separately defined function. This keeps the code short and focused when the logic is simple.
map(), filter(), and sorted().def functions if the logic is complex or reused.map() to cube a list of numbers.filter() to extract odd numbers from a list.sorted() to sort a list of tuples by the second element.def function as a lambda (if the logic is simple enough).