Applications of Lambda Functions – Programs
Program 1: Sorting a List of Tuples Based on the Second Element
# List of tuples
data = [(1, 'apple'), (3, 'banana'), (2, 'cherry'), (4, 'date')]
# Sort based on the second element in each tuple
sorted_data = sorted(data, key=lambda x: x[1])
print("Sorted by second element:", sorted_data)
Expected Output:
Sorted by second element: [(1, 'apple'), (3, 'banana'), (2, 'cherry'), (4, 'date')]
Program 2: Using Lambda with map
to Calculate Squares of a List of Numbers
# List of numbers
numbers = [1, 2, 3, 4, 5]
# Apply lambda with map to square each number
squared_numbers = list(map(lambda x: x ** 2, numbers))
print("Squared Numbers:", squared_numbers)
Expected Output:
Squared Numbers: [1, 4, 9, 16, 25]
Program 3: Using Lambda with filter
to Get Names Longer Than 5 Characters
# List of names
names = ["Alice", "Bob", "Charlie", "David", "Edward"]
# Filter names longer than 5 characters
long_names = list(filter(lambda name: len(name) > 5, names))
print("Names longer than 5 characters:", long_names)
Expected Output:
Names longer than 5 characters: ['Charlie', 'Edward']
Program 4: Using Lambda with reduce
to Calculate Product of List Elements
from functools import reduce
# List of numbers
numbers = [1, 2, 3, 4, 5]
# Reduce to calculate the product of all elements
product = reduce(lambda x, y: x * y, numbers)
print("Product of all elements:", product)
Expected Output:
Product of all elements: 120
Program 5: Lambda Function to Find the Maximum of Two Numbers
# Lambda to find the maximum of two numbers
max_value = lambda x, y: x if x > y else y
# Example usage
print("Max of 10 and 20:", max_value(10, 20))
Expected Output:
Max of 10 and 20: 20