Filter and Transform
In real programs, we constantly need to filter data (keep only what we want) and transform it (change every element in some way). These are two of the most common operations in programming, and we've already seen them, now let's practice them as a skill
Filtering means: go through a list and keep only the elements that match a condition
scores = [45, 82, 67, 91, 38, 74, 55, 96]
passed = []
for s in scores:
if s >= 50:
passed.append(s)
print(passed)
Output [82, 67, 91, 74, 55, 96]
Or with list comprehension
passed = [s for s in scores if s >= 50]
Same result, shorter code
Transforming means: apply an operation to every element
prices = [10.0, 25.5, 8.0, 42.0]
with_tax = []
for price in prices:
with_tax.append(round(price * 1.19, 2))
print(with_tax)
Output [11.9, 30.35, 9.52, 49.98]
Or with list comprehension
with_tax = [round(price * 1.19, 2) for price in prices]
The real power comes when we combine both: filter first, then transform (or vice versa)
players = [
{"name": "Tommy", "score": 95, "online": True},
{"name": "Lance", "score": 42, "online": False},
{"name": "Cortez", "score": 88, "online": True},
{"name": "Phil", "score": 71, "online": True},
{"name": "Sonny", "score": 33, "online": False}
]
online_names = []
for player in players:
if player["online"]:
online_names.append(player["name"])
print(online_names)
Output ['Tommy', 'Cortez', 'Phil']
We filtered (only online players) and transformed (extracted just the name). With list comprehension
online_names = [p["name"] for p in players if p["online"]]
Let's do a more complex example. We have student grades and we want to
- Filter out anyone who failed (below 50)
- Transform the remaining grades by adding a 5-point bonus
- Cap at 100 (nobody can go above 100)
grades = [45, 82, 67, 91, 38, 74, 55, 96]
result = []
for grade in grades:
if grade >= 50:
boosted = grade + 5
if boosted > 100:
boosted = 100
result.append(boosted)
print(result)
Output [87, 72, 96, 79, 60, 100]
With comprehension and min() to cap
result = [min(g + 5, 100) for g in grades if g >= 50]
Mission: Power Grid Filter
The station's reactors report power readings in a list named readings. Engineering wants to focus on the stable reactors and give them a small boost, but no reactor may exceed 100.
- Filter: keep only readings that are
>= 50(the stable reactors). - Transform: add a 5-point boost to each kept reading, capped at 100 (use
min(reading + 5, 100)so nothing goes over). - Print
Boosted:followed by the resulting list. - Print
Stable reactors:followed by how many made the cut. - Print
Average:followed by the average of the boosted readings, rounded to a whole number withround().
Output
Boosted: [87, 72, 96, 79, 60, 100, 65]
Stable reactors: 7
Average: 80