Python Basics — Lambda & Functional Practice Exercises
Lambda & Functional — Practice Exercises
Test your understanding of lambda expressions, map(), filter(), reduce(), and custom sorting.
Exercise 1 — Transform and Filter
Given a list of temperatures in Celsius, use map() to convert them to Fahrenheit, then use filter() to keep only temperatures above 100°F.
celsius = [0, 20, 37, 45, 55, 100]
# Formula: F = C × 9/5 + 32
# Expected: [100.4, 113.0, 131.0, 212.0]
Show Solution
celsius = [0, 20, 37, 45, 55, 100]
fahrenheit = map(lambda c: c * 9/5 + 32, celsius)
hot = list(filter(lambda f: f > 100, fahrenheit))
print(hot) # [98.6, 113.0, 131.0, 212.0]
# Wait — 37°C = 98.6°F which is NOT above 100
# Correct expected output: [113.0, 131.0, 212.0]
# Let me verify:
# 0°C = 32°F, 20°C = 68°F, 37°C = 98.6°F, 45°C = 113°F, 55°C = 131°F, 100°C = 212°F
# More Pythonic (list comprehension):
result = [c * 9/5 + 32 for c in celsius if c * 9/5 + 32 > 100]
print(result) # [113.0, 131.0, 212.0]
Exercise 2 — Word Frequency with reduce
Use reduce() to count the frequency of each word in a list, producing a dictionary.
from functools import reduce
words = ["apple", "banana", "apple", "cherry", "banana", "apple"]
# Expected: {'apple': 3, 'banana': 2, 'cherry': 1}
Show Solution
from functools import reduce
words = ["apple", "banana", "apple", "cherry", "banana", "apple"]
freq = reduce(
lambda acc, word: {**acc, word: acc.get(word, 0) + 1},
words,
{}
)
print(freq) # {'apple': 3, 'banana': 2, 'cherry': 1}
# More Pythonic alternative using collections.Counter:
from collections import Counter
freq = Counter(words)
print(dict(freq)) # {'apple': 3, 'banana': 2, 'cherry': 1}
Exercise 3 — Custom Sort
Sort the following list of dictionaries by:
- Primary: department (ascending)
- Secondary: salary (descending — highest first)
employees = [
{"name": "Alice", "department": "Engineering", "salary": 90000},
{"name": "Bob", "department": "Marketing", "salary": 70000},
{"name": "Charlie", "department": "Engineering", "salary": 85000},
{"name": "Diana", "department": "Marketing", "salary": 75000},
{"name": "Eve", "department": "Engineering", "salary": 95000},
]
Show Solution
employees = [
{"name": "Alice", "department": "Engineering", "salary": 90000},
{"name": "Bob", "department": "Marketing", "salary": 70000},
{"name": "Charlie", "department": "Engineering", "salary": 85000},
{"name": "Diana", "department": "Marketing", "salary": 75000},
{"name": "Eve", "department": "Engineering", "salary": 95000},
]
sorted_emps = sorted(
employees,
key=lambda e: (e["department"], -e["salary"])
)
for emp in sorted_emps:
print(f"{emp['department']:15} {emp['name']:10} ₹{emp['salary']}")
# Engineering Eve ₹95000
# Engineering Alice ₹90000
# Engineering Charlie ₹85000
# Marketing Diana ₹75000
# Marketing Bob ₹70000
Using a tuple key with -salary reverses the salary order.
Exercise 4 — Pipeline Processing
Create a data processing pipeline using map() and filter() that:
- Takes a list of raw price strings:
["$10.50", "$25.00", "$5.75", "$150.00", "$8.99"] - Strips the
$sign and converts to float - Applies an 18% tax
- Keeps only items over $10 (after tax)
- Rounds to 2 decimal places
Show Solution
raw_prices = ["$10.50", "$25.00", "$5.75", "$150.00", "$8.99"]
# Step 1-2: Strip $ and convert to float
prices = map(lambda p: float(p.replace("$", "")), raw_prices)
# Step 3: Apply 18% tax
with_tax = map(lambda p: p * 1.18, prices)
# Step 4: Filter > $10
above_10 = filter(lambda p: p > 10, with_tax)
# Step 5: Round to 2 decimal places
final = list(map(lambda p: round(p, 2), above_10))
print(final) # [12.39, 29.5, 177.0, 10.61]
# All-in-one with list comprehension:
final = [
round(float(p.replace("$", "")) * 1.18, 2)
for p in raw_prices
if float(p.replace("$", "")) * 1.18 > 10
]
print(final) # [12.39, 29.5, 177.0, 10.61]
Exercise 5 — Function Toolkit
Create these three utility functions using only lambda and functional tools:
negate— takes a predicate function and returns the oppositecompose— takes two functions and returns their compositionapply_all— takes a list of functions and a value, returns a list of results
# negate
is_even = lambda x: x % 2 == 0
is_odd = negate(is_even)
print(is_odd(3)) # True
print(is_odd(4)) # False
# compose
add_one = lambda x: x + 1
double = lambda x: x * 2
double_then_add = compose(add_one, double)
print(double_then_add(5)) # add_one(double(5)) = 11
# apply_all
funcs = [lambda x: x+1, lambda x: x*2, lambda x: x**2]
print(apply_all(funcs, 5)) # [6, 10, 25]
Show Solution
# negate — returns opposite of a predicate
negate = lambda func: lambda *args: not func(*args)
is_even = lambda x: x % 2 == 0
is_odd = negate(is_even)
print(is_odd(3)) # True
print(is_odd(4)) # False
# compose — applies f(g(x))
compose = lambda f, g: lambda *args: f(g(*args))
add_one = lambda x: x + 1
double = lambda x: x * 2
double_then_add = compose(add_one, double)
print(double_then_add(5)) # 11
# apply_all — applies each function to the value
apply_all = lambda funcs, val: list(map(lambda f: f(val), funcs))
funcs = [lambda x: x+1, lambda x: x*2, lambda x: x**2]
print(apply_all(funcs, 5)) # [6, 10, 25]
Scoring Guide
| Score | Level |
|---|---|
| 5/5 | ⭐ Functional programming pro — master of map, filter, reduce |
| 3-4/5 | 👍 Solid understanding — practice chaining operations |
| 1-2/5 | 📚 Review lambda syntax, map/filter patterns, and sorted() |
Next chapter: Modules & Packages →