LAMBDA
In Python, lambda is used to create anonymous functions. These functions are also known as lambda functions. They are defined using the lambda keyword, followed by a list of parameters, a colon, and an expression. Lambda functions are often used for short, simple operations and are commonly employed in situations where a small function is needed for a short period and doesn't require a formal function definition using def.
Here's the basic syntax of a lambda function:
lambda arguments: expression
Here's a simple example:
# Regular function
def add(x, y):
return x + y
# Equivalent lambda function
add_lambda = lambda x, y: x + y
# Using the functions
result1 = add(5, 3)
result2 = add_lambda(5, 3)
print(result1) # Output: 8
print(result2) # Output: 8
Lambda functions are often used in situations where a short function is needed, such as with higher-order functions like map()
, filter()
, and sorted()
. Here are a few examples:
# Example using map() with lambda
numbers = [1, 2, 3, 4, 5]
squared = map(lambda x: x**2, numbers)
print(list(squared)) # Output: [1, 4, 9, 16, 25]
# Example using filter() with lambda
even_numbers = filter(lambda x: x % 2 == 0, numbers)
print(list(even_numbers)) # Output: [2, 4]
# Example using sorted() with lambda
words = ['apple', 'banana', 'kiwi', 'orange']
sorted_words = sorted(words, key=lambda x: len(x))
print(sorted_words) # Output: ['kiwi', 'apple', 'banana', 'orange']