Unit 4 Β· Lesson 3
Iterating Over Lists
Combine loops with lists to search, filter, transform, and analyze data.
Use
for item in list to iterateAccess indices with
enumerate()Build filtered lists
Find max/min values and positions
Looping Through Lists
The most natural way to process every item in a list:
colors = ["red", "green", "blue"]
for color in colors:
print(color)
# red, green, blue
When You Need the Index Too
# Option 1: enumerate() β preferred!
for i, color in enumerate(colors):
print(f"{i}: {color}")
# Option 2: range(len()) β when you need index math
for i in range(len(colors)):
print(f"{i}: {colors[i]}")
Common list patterns: Sum all values (accumulator), find max/min, filter into a new list, transform each element, search for a value. You learned the patterns in Unit 3 β now apply them to real lists!
Practice Time
Challenges
Challenge 1: Grade Calculator
Guided
Calculate the average of a list of grades.
Instructions: Given
grades, calculate the total and average.Hint:
for g in grades: total += gChallenge 2: Search & Count
Guided
Count how many times a target appears in a list.
Instructions: Count how many times
target appears in numbers. Store in count.Hint:
for n in numbers: if n == target: count += 1Challenge 3: High Scores
Solo
Find the highest and lowest scores and their positions.
Instructions: Find
highest, lowest, high_pos (index of highest), and low_pos (index of lowest). Don't use built-in max()/min().Hint: Use
for i, s in enumerate(scores): then compare s to highest/lowest, updating both value and position.Challenge 4: List Filter
Stretch
Build a new list containing only the even numbers.
Instructions: From
numbers, create evens containing only the even values (in order).Hint:
for n in numbers: if n % 2 == 0: evens.append(n)