# Regular function
def add(x, y):
return x + y
# Equivalent lambda function
= lambda x, y: x + y
add_lambda
# Usage
print(add(1, 2))
print(add_lambda(1, 2))
3
3
Unit 11
A lambda function is a concise way to write a function that takes input, performs an operation, and returns a result—all in a single line.
Consider this expression: lambda a, b: a+b
, which represents a lambda function that returns the sum of its two arguments a and b. Let’s compare this to a regular function:
# Regular function
def add(x, y):
return x + y
# Equivalent lambda function
add_lambda = lambda x, y: x + y
# Usage
print(add(1, 2))
print(add_lambda(1, 2))
3
3
When you need a short function for a temporary use case, often in higher-order functions. For example:
Sort a list
Sort a list of tuples by the second value:
pairs = [(1, 2), (3, 1), (5, 3)]
# Regular approach
def extract_second_value(x):
return x[1]
print(sorted(pairs, key=extract_second_value))
# Equivalent lambda approach
print(sorted(pairs, key=lambda x: x[1]))
[(3, 1), (1, 2), (5, 3)]
[(3, 1), (1, 2), (5, 3)]
Filter a list
# Regular approach
def contains_letter(word, letter):
return letter in word
words = []
for word in ["Hello", "world", "it's", "me"]:
if contains_letter(word, "o"):
words.append(word)
print(words)
# Equivalent lambda approach using the filter function
words = ["Hello", "world", "it's", "me"]
words = list(filter(lambda word: "o" in word, words))
print(words)
['Hello', 'world']
['Hello', 'world']