Python · Syntax · Intermediate
lambda, map, filter, reduce
Functional tools for transforming and filtering collections without writing explicit loops.
Quick topic start and explanations before exercises (exercises below):
lambda as key=, the operator module, and named functions vs lambda
#map/filter vs comprehensions, functools.partial, and decision guide
#Exercises:
Double with map
#Write a function that takes a list of numbers and returns a new list where each number is doubled. Use map() with a lambda.
def double_all(numbers):
pass
result = double_all([1, 2, 3, 4, 5])
print(result)
Solution
def double_all(numbers):
return list(map(lambda n: n * 2, numbers))
result = double_all([1, 2, 3, 4, 5])
print(result)
Filter positives
#Write a function that takes a list of numbers and returns only the positive ones. Use filter() with a lambda.
def keep_positives(numbers):
pass
result = keep_positives([3, -1, 4, -1, -5, 9, -2, 6])
print(result)
Solution
def keep_positives(numbers):
return list(filter(lambda n: n > 0, numbers))
result = keep_positives([3, -1, 4, -1, -5, 9, -2, 6])
print(result)
Sort by length
#Write a function that takes a list of strings and returns them sorted by length, shortest first. Use sorted() with a lambda key.
def sort_by_length(words):
pass
result = sort_by_length(["banana", "fig", "apple", "kiwi"])
print(result)
Solution
def sort_by_length(words):
return sorted(words, key=lambda w: len(w))
result = sort_by_length(["banana", "fig", "apple", "kiwi"])
print(result)
Product with reduce
#Write a function that takes a list of numbers and returns their product (multiply all elements together). Use reduce() from functools.
from functools import reduce
def product(numbers):
pass
result = product([1, 2, 3, 4, 5])
print(result)
Solution
from functools import reduce
def product(numbers):
return reduce(lambda acc, n: acc * n, numbers)
result = product([1, 2, 3, 4, 5])
print(result)
Apply a discount
#Write a function that takes a list of prices and a discount percentage, and returns a new list with the discount applied to each price. Use map() with a lambda.
def apply_discount(prices, discount_percent):
pass
result = apply_discount([100, 200, 50, 80], 10)
print(result)
Solution
def apply_discount(prices, discount_percent):
return list(map(lambda p: p * (1 - discount_percent / 100), prices))
result = apply_discount([100, 200, 50, 80], 10)
print(result)
Filter even, square the rest
#Write a function that takes a list of numbers, removes the even ones, and returns the squares of what remains. Chain filter() and map().
def odd_squares(numbers):
pass
result = odd_squares([1, 2, 3, 4, 5, 6, 7])
print(result)
Solution
def odd_squares(numbers):
return list(map(lambda n: n ** 2, filter(lambda n: n % 2 != 0, numbers)))
result = odd_squares([1, 2, 3, 4, 5, 6, 7])
print(result)
Sort objects by attribute
#Write a function that takes a list of dictionaries, each with 'name' and 'score' keys, and returns the list sorted by score in descending order.
def sort_by_score(players):
pass
players = [
{"name": "Alice", "score": 82},
{"name": "Bob", "score": 95},
{"name": "Carol", "score": 71},
]
result = sort_by_score(players)
print(result)
Solution
def sort_by_score(players):
return sorted(players, key=lambda p: p["score"], reverse=True)
players = [
{"name": "Alice", "score": 82},
{"name": "Bob", "score": 95},
{"name": "Carol", "score": 71},
]
result = sort_by_score(players)
print(result)
Maximum by key
#Write a function that takes a list of strings and returns the longest one. Use max() with a lambda key.
def longest_word(words):
pass
result = longest_word(["cat", "elephant", "ox", "hippopotamus"])
print(result)
Solution
def longest_word(words):
return max(words, key=lambda w: len(w))
result = longest_word(["cat", "elephant", "ox", "hippopotamus"])
print(result)
Filter by multiple conditions
#Write a function that takes a list of numbers and returns only those that are both positive and even.
def positive_evens(numbers):
pass
result = positive_evens([-4, 3, -2, 8, 0, 6, -7, 10])
print(result)
Solution
def positive_evens(numbers):
return list(filter(lambda n: n > 0 and n % 2 == 0, numbers))
result = positive_evens([-4, 3, -2, 8, 0, 6, -7, 10])
print(result)
Cumulative sum with reduce
#Write a function that takes a list of numbers and returns the largest sum you can reach by adding elements from left to right (i.e., the maximum value of any prefix sum). Use reduce() from functools.
from functools import reduce
def max_prefix_sum(numbers):
pass
result = max_prefix_sum([1, -3, 2, 5, -1, 3])
print(result)
Solution
from functools import reduce
def max_prefix_sum(numbers):
prefix_sums = []
reduce(lambda acc, n: (prefix_sums.append(acc + n) or (acc + n)), numbers, 0)
return max(prefix_sums)
# Or more clearly:
def max_prefix_sum(numbers):
total = 0
best = 0
for n in numbers:
total += n
best = max(best, total)
return best
result = max_prefix_sum([1, -3, 2, 5, -1, 3])
print(result)