Comprehensions & Functional Tools
Write expressive one-liners with list, dict, and set comprehensions, plus map, filter, functools.reduce, partial, and itertools.
Part 1: What You Will Learn
- Build list, set, and dictionary comprehensions.
- Use conditional expressions inside comprehensions.
- Apply
map(),filter(), andfunctools.reduce(). - Use
partial()and selecteditertoolshelpers when they improve readability.
Part 2: Key Concepts
Comprehensions are concise syntax for transforming or filtering iterables. Functional tools solve related problems by passing functions as values. The goal is not to force every loop into one line; use these tools when they make the transformation clearer.
Part 3: Topic-Specific Code Example
from functools import reduce, partial
from itertools import groupby
marks = [42, 67, 81, 55, 93, 38]
passed = [mark for mark in marks if mark >= 50]
grade_map = {
mark: ("Distinction" if mark >= 80 else "Pass" if mark >= 50 else "Fail")
for mark in marks
}
unique_bands = {mark // 10 * 10 for mark in marks}
curved = list(map(lambda mark: min(mark + 5, 100), marks))
strong_results = list(filter(lambda mark: mark >= 70, curved))
total = reduce(lambda running, mark: running + mark, marks, 0)
round_to = partial(round, ndigits=1)
average = round_to(total / len(marks))
sorted_marks = sorted(marks, key=lambda m: m >= 50)
for passed_group, values in groupby(sorted_marks, key=lambda m: m >= 50):
print("Pass" if passed_group else "Fail", list(values))
print("Passed:", passed)
print("Grades:", grade_map)
print("Bands:", unique_bands)
print("Curved >= 70:", strong_results)
print("Average:", average)Part 4: How the Example Works
The three comprehensions create a filtered list, a lookup dictionary, and a set of unique score bands. map() transforms every value, filter() keeps selected values, and reduce() combines values into one result. In ordinary Python, a comprehension is often clearer than map()/filter(); knowing both styles helps you read real-world code.
Part 5: Hands-On Practice
Mini project โ Sales Analyzer. Starting with a list of transaction dictionaries, create a comprehension for high-value sales, a dictionary comprehension for tax-inclusive totals, and use reduce() to calculate grand revenue.
Part 6: Next Steps
Run and modify the examples in Visual Studio 2026, then continue to Lesson 14. Return to Python Tutorial Home to review the complete curriculum.