In Python, Lambda function is a small anonymous function (without a function name) defined using the "lambda" keyword.
Lambda functions can take any number of arguments, but they can only have one expression.
They are often used when we need a simple function for a short period and don't want to formally define a named function using the "def" keyword.
Lambda functions are particularly useful in functional programming concepts like map, filter, and reduce.
lambda arguments: expression
# Define a Number function to calculate the square of a number def square(number): return number**2 print(square(5)) # Output: 25 print(square(8)) # Output: 64 print(square(10)) # Output: 100
# Define a lambda function to calculate the square of a number square = lambda number: number**2 print(square(5)) # Output: 25 print(square(8)) # Output: 64 print(square(10)) # Output: 100
Lambda function can accept nth number of arguments but return one result.
# Define a lambda function to add two numbers add = lambda num1, num2: num1 + num2 print(add(5, 7)) # Output: 12 print(add(10, -7)) # Output: 3 print(add(30, -40)) # Output: -10
Lambda functions are often used with built-in functions like map(), filter(), and sorted().
map, and filter functions accept two arguments, the first argument as a function that performs actions and the second argument as data. In our case it is a `numbers` list, it will loop over each item from the list and the first argument function will perform the task on it and return one result.
# Using lambda with map() to double each element of a list numbers = [1, 2, 3, 4, 5] squaredNumbers = list(map(lambda x: x * 2, numbers)) print(squaredNumbers) # Output: [2, 4, 6, 8, 10]
# Using lambda with filter() to filter even numbers from a list evenNumbers = list(filter(lambda x: x % 2 == 0, numbers)) print(evenNumbers) # Output: [2, 4]
# Using lambda with sorted() method # It will sort a list of tuples based on the second element inside tuples pairs = [(5, 'five'), (6, 'six'), (2, 'two')] sortedPairs = sorted(pairs, key=lambda x: x[1]) print(sortedPairs) # Output: [(5, 'five'), (6, 'six'), (2, 'two')]
Lambda functions offer a concise way to create simple functions without the need for formal function definitions.
However, they should be used judiciously, especially when readability and maintainability are important, as complex lambda expressions can make code harder to understand.