Lesson explanation
After this lesson, you will be able to:
.append()..get().Loops can construct a collection, not just print its values. Start with an empty destination, then add values as you process the source. For a list, use .append() to add each selected result while preserving its encounter order.
Filtering uses a condition inside the loop: some source items are appended and others are skipped. Keep the input collection unchanged when it represents data you may need later; editing a list while iterating over that same list can skip elements unexpectedly.
A dictionary is useful for counts and groups. counts.get(key, 0) retrieves the current count or starts at zero. For grouping, initialize a list the first time a category appears, then append its items. You are combining methods from earlier lessons with functions, conditions, and loops from Unit 1.
raw_regions = [" EU ", "Us", " APAC "]
regions = []
for region in raw_regions:
regions.append(region.strip().lower())
print(regions)Output:
['eu', 'us', 'apac']Each cleaned value is appended to the new list.
scores = [31, 0, 18, -3]
valid_scores = []
for score in scores:
if score >= 0:
valid_scores.append(score)
print(valid_scores)Output:
[31, 0, 18]The source stays intact; only valid values enter the result.
states = ["open", "closed", "open"]
counts = {}
for state in states:
counts[state] = counts.get(state, 0) + 1
print(counts["open"])Output:
2The fallback count starts an unseen key at zero.
requests = [("api", "urgent"), ("worker", "normal"), ("mail", "urgent")]
groups = {}
for service, category in requests:
if category not in groups:
groups[category] = []
groups[category].append(service)
print(groups["urgent"])Output:
['api', 'mail']A grouped dictionary combines a key with an ordered list of matching values.
| Goal | Pattern |
|---|---|
| Start an output list | results = [] |
| Add the next selected value | results.append(value) |
| Filter values | if condition: inside a loop |
| Update a count | counts[key] = counts.get(key, 0) + 1 |
| Start a new category | groups[key] = [] |
KeyError.