Python Lambda
Master anonymous functions and functional programming concepts
β‘ Understanding Lambda Functions
A lambda function is a small anonymous function. A lambda function can take any number of arguments, but can only have one expression. They're perfect for short, simple operations that don't warrant a full function definition.
# Lambda function examples
square = lambda x: x**2 # Squares a number
add = lambda x,y: x + y # Adds two numbers
greet = lambda name: f"Hello {name}" # Create greeting
is_even = lambda x: x % 2 == 0 # Checks if no.is even
Lambda Syntax
The syntax for a lambda function is simple and concise:
Basic Syntax
lambda arguments : expression
The expression is executed and the result is returned.
# A lambda function that adds 10 to the number passed in as an argument
x = lambda a : a + 10
print(x(5)) # Output: 15
# Compare with regular function
def add_ten(a):
return a + 10
print(add_ten(5)) # Output: 15
Lambda Functions with Multiple Arguments
Lambda functions can take any number of arguments, making them versatile for various operations.
# A lambda function that multiplies argument a with argument b
multiply = lambda a, b : a * b
print(multiply(5, 6)) # Output: 30
# A lambda function that sums argument a, b, and c
sum_three = lambda a, b, c : a + b + c
print(sum_three(5, 6, 2)) # Output: 13
# Lambda with default arguments
greet = lambda name, greeting="Hello" : f"{greeting}, {name}!"
print(greet("Alice")) # Output: Hello, Alice!
print(greet("Bob", "Hi")) # Output: Hi, Bob!
Why Use Lambda Functions?
The power of lambda is better shown when you use them as an anonymous function inside another function.
def myfunc(n):
return lambda a : a * n
# Create specialized functions
mydoubler = myfunc(2)
mytripler = myfunc(3)
myquadrupler = myfunc(4)
print(mydoubler(11)) # Output: 22
print(mytripler(11)) # Output: 33
print(myquadrupler(11)) # Output: 44
# Real-world example: Tax calculator
def create_tax_calculator(tax_rate):
return lambda amount: amount * tax_rate
# Create different tax calculators
sales_tax = create_tax_calculator(0.08) # 8% sales tax
luxury_tax = create_tax_calculator(0.15) # 15% luxury tax
print(f"Sales tax on $100: ${sales_tax(100):.2f}") # Output: Sales tax on $100: $8.00
print(f"Luxury tax on $1000: ${luxury_tax(1000):.2f}") # Output: Luxury tax on $1000: $150.00
Lambda with Built-in Functions
Lambda functions are commonly used with higher-order functions like
filter()
,
map()
, and
sort()
.
filter()
Filter elements based on condition
# Filter out even numbers
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers) # [2, 4, 6, 8, 10]
map()
Transform each element in a collection
# Square each number
numbers = [1, 2, 3, 4, 5]
squared_numbers = list(map(lambda x: x**2, numbers))
print(squared_numbers) # [1, 4, 9, 16, 25]
sort()
Custom sorting with key function
# Sort by second element
pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]
pairs.sort(key=lambda pair: pair[1])
print(pairs) # [(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')]
Advanced Lambda Examples
Explore more complex use cases and patterns with lambda functions.
# Example 1: Data processing with lambda
employees = [
{'name': 'Alice', 'salary': 50000, 'department': 'Engineering'},
{'name': 'Bob', 'salary': 60000, 'department': 'Marketing'},
{'name': 'Charlie', 'salary': 55000, 'department': 'Engineering'},
{'name': 'Diana', 'salary': 65000, 'department': 'Sales'}
]
# Filter high earners (salary > 55000)
high_earners = list(filter(lambda emp: emp['salary'] > 55000, employees))
print("High earners:", [emp['name'] for emp in high_earners])
# Get all salaries with 10% bonus
salaries_with_bonus = list(map(lambda emp: emp['salary'] * 1.1, employees))
print("Salaries with bonus:", salaries_with_bonus)
# Sort by salary (descending)
employees_by_salary = sorted(employees, key=lambda emp: emp['salary'], reverse=True)
print("Sorted by salary:", [f"{emp['name']}: ${emp['salary']}" for emp in employees_by_salary])
# Example 2: String processing
words = ['python', 'lambda', 'function', 'programming', 'code']
# Filter words longer than 6 characters
long_words = list(filter(lambda word: len(word) > 6, words))
print("Long words:", long_words)
# Capitalize all words
capitalized = list(map(lambda word: word.capitalize(), words))
print("Capitalized:", capitalized)
# Sort by word length
sorted_by_length = sorted(words, key=lambda word: len(word))
print("Sorted by length:", sorted_by_length)
# Example 3: Mathematical operations
import math
# Create a list of mathematical functions
math_operations = {
'square': lambda x: x ** 2,
'cube': lambda x: x ** 3,
'sqrt': lambda x: math.sqrt(x) if x >= 0 else None,
'factorial': lambda x: math.factorial(int(x)) if x >= 0 and x == int(x) else None
}
number = 5
for operation, func in math_operations.items():
result = func(number)
if result is not None:
print(f"{operation}({number}) = {result}")
# Example 4: Conditional lambda (ternary operator)
# Find absolute value
abs_value = lambda x: x if x >= 0 else -x
print(f"Absolute value of -10: {abs_value(-10)}") # Output: 10
print(f"Absolute value of 15: {abs_value(15)}") # Output: 15
# Grade classifier
grade_classifier = lambda score: (
'A' if score >= 90 else
'B' if score >= 80 else
'C' if score >= 70 else
'D' if score >= 60 else
'F'
)
scores = [95, 87, 76, 65, 45]
grades = list(map(grade_classifier, scores))
print("Grades:", grades) # Output: ['A', 'B', 'C', 'D', 'F']
Lambda vs Regular Functions
Understanding when to use lambda functions versus regular functions:
β‘ Lambda Functions
π§ Regular Functions
ποΈ Practice Exercise: Sort a List of Dictionaries
You have a list of dictionaries, where each dictionary represents a student with 'name' and 'grade' keys. Use a lambda function with the
sort()
method to sort the list by 'grade' in ascending order.
# Student data
students = [
{'name': 'Alice', 'grade': 85},
{'name': 'Bob', 'grade': 92},
{'name': 'Charlie', 'grade': 78},
{'name': 'David', 'grade': 95}
]
# Sort the list of students by their grade
students.sort(key=lambda student: student['grade'])
print("Students sorted by grade:")
for student in students:
print(f"{student['name']}: {student['grade']}")
# Expected Output:
# Charlie: 78
# Alice: 85
# Bob: 92
# David: 95
# Bonus: Sort by name alphabetically
students_by_name = sorted(students, key=lambda student: student['name'])
print("\nStudents sorted by name:")
for student in students_by_name:
print(f"{student['name']}: {student['grade']}")
# Bonus: Find top performer
top_student = max(students, key=lambda student: student['grade'])
print(f"\nTop performer: {top_student['name']} with grade {top_student['grade']}")