Learning goals
Transform and filter collections concisely and understand small anonymous functions and lazy map and filter results.
Explanation
A list comprehension has the form [expression for item in iterable if condition]. The optional condition filters inputs before the expression builds each output. Dictionary comprehensions create key and value pairs; set comprehensions create unique results.
A lambda is an anonymous function with one expression. It is useful for a short callback, such as a sorting key. Use def when the logic needs several steps, validation, or a meaningful reusable name. map applies a function to items; filter retains items whose predicate is truthy. Both return iterators in Python 3.
Example 1 Transforming scores
scores = [35, 60, 80, 45, 90]
passing = [score for score in scores if score >= 50]
bonus = [min(score + 5, 100) for score in scores]
squares = {number: number ** 2 for number in range(1, 4)}
lengths = {len(word) for word in ["cat", "dog", "bird"]}
print(passing)
print(bonus)
print(squares)
print(sorted(lengths))Expected output:
[60, 80, 90]
[40, 65, 85, 50, 95]
{1: 1, 2: 4, 3: 9}
[3, 4]The first comprehension filters without changing the selected scores. The second changes every score and caps the result. Duplicate lengths collapse in the set.
Example 2 Lambda and iterator tools
students = [("Ali", 75), ("Sara", 92), ("Bilal", 80)]
ranked = sorted(students, key=lambda student: student[1],
reverse=True)
print(ranked)
print(list(map(lambda number: number * 2, [1, 2, 3])))
print(list(filter(lambda number: number % 2 == 0,
[1, 2, 3, 4, 5, 6])))Expected output:
[('Sara', 92), ('Bilal', 80), ('Ali', 75)]
[2, 4, 6]
[2, 4, 6]The key function returns the score from each pair. sorted returns a new list. list consumes the map or filter iterator so its values can be displayed. A consumed iterator is not automatically reset.
Common mistakes
Do not use a comprehension only to produce side effects, such as printing. Deeply nested comprehensions can hide the logic; an ordinary loop may be clearer. A dictionary comprehension overwrites an earlier value when two inputs produce the same key.
Student tasks
1. Build squares for numbers 1 through 10, keeping only the even input numbers. Expected: [4, 16, 36, 64, 100].
2. Build a dictionary mapping "apple", "banana", and "kiwi" to their lengths.
3. Sort product pairs by price from lowest to highest using a lambda.
4. Write the same even-number filter using a loop, a comprehension, and filter. Verify equal results.
Completion check: explain transformation versus filtering and show one lambda used as a callback.