Lambda functions

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 to Use Lambda Functions?

When you need a short function for a temporary use case, often in higher-order functions. For example:

Sort a list

numbers = [2, 4, 1, 3]
print(sorted(numbers))
[1, 2, 3, 4]

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']
#11-03: Filter even numbers

Following the example of filtering a list of words, filter a list of numbers to keep only even ones. Use the filter function with a lambda expression to achieve this.

Solution
numbers = [1, 2, 3, 4, 5, 6]
evens = list(filter(lambda x: x % 2 == 0, numbers))
print(evens)
[2, 4, 6]