Advanced Lambda Functions

Python FunctionsFree Lesson

Advertisement

Advanced Lambda Functions

Lambda patterns, closures, and functional programming with lambda.

Overview

Master advanced lambda usage.

Lambda with map/filter

numbers = [1, 2, 3, 4, 5]

# Map
squared = list(map(lambda x: x**2, numbers))
print(squared)  # [1, 4, 9, 16, 25]

# Filter
evens = list(filter(lambda x: x % 2 == 0, numbers))
print(evens)  # [2, 4]

# Reduce
from functools import reduce
product = reduce(lambda x, y: x * y, numbers)
print(product)  # 120

# Chained operations
result = list(map(lambda x: x**2, filter(lambda x: x > 2, numbers)))
print(result)  # [9, 16, 25]

Lambda as Arguments

# Sort by key
students = [("Alice", 85), ("Bob", 92), ("Charlie", 78)]
sorted_students = sorted(students, key=lambda x: x[1], reverse=True)
print(sorted_students)  # [('Bob', 92), ('Alice', 85), ('Charlie', 78)]

# Dictionary operations
data = {"a": 3, "b": 1, "c": 2}
sorted_keys = sorted(data.keys(), key=lambda k: data[k])
print(sorted_keys)  # ['b', 'c', 'a']

# max/min with key
words = ["apple", "banana", "cherry"]
longest = max(words, key=len)
print(longest)  # banana

Lambda Closures

# Function factories
def multiplier(n):
    return lambda x: x * n

double = multiplier(2)
triple = multiplier(3)

print(double(5))  # 10
print(triple(5))  # 15

# Conditional lambda
def action(action_type):
    actions = {
        "add": lambda x, y: x + y,
        "subtract": lambda x, y: x - y,
        "multiply": lambda x, y: x * y,
    }
    return actions.get(action_type)

add = action("add")
print(add(5, 3))  # 8

Practice

Use lambda to implement a simple event system.

Advertisement

Need Expert Python Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement