Skill 9: Iteration with Lists (Python)
1. Understanding Local Variables in Loops
What to Teach
Local variables store and accumulate values during iteration. Python uses regular variable assignment (no special var keyword needed) and standard assignment operators.
Basic Variable Usage
# initialize accumulator variables
total = 0
count = 0
# variables can be updated
total = total + 10
count = count + 1
total += 10
count += 1
When to Use Local Variables
In python, mutation is used pervasively. In our class, we try to only use it for accumulating values during iteration, though as students encounter libraries that rely on mutation, they will inevitably have to understand other uses, e.g.:
- Counting occurrences
- Building results incrementally
- Tracking state that changes over time
Teaching Examples
Good Example:
def calculate_total(prices: list[float]) -> float:
"""calculate total of all prices"""
total = 0.0
for price in prices:
total += price
return total
def test_calculate_total():
assert calculate_total([1.0, 2.5, 3.0]) == 6.5
assert calculate_total([]) == 0.0
assert calculate_total([10.0]) == 10.0
assert calculate_total([1.25, 2.75, 0.5]) == 4.5
What to Point Out:
- Variables are initialized before the loop
- Use meaningful names that describe what's being accumulated
- Variables maintain their values across loop iterations
Common Student Mistakes to Watch For
-
Forgetting to initialize accumulator variables
# BAD - total not initialized
def bad_sum(numbers: list[int]) -> int:
for num in numbers:
total += num # total is not defined
return total -
Declaring variables inside the loop
# BAD - reinitializing inside loop
def bad_accumulate(numbers: list[int]) -> int:
for num in numbers:
total = 0 # gets reset every iteration
total += num
return total
2. Basic for ... in Loop Structure
What to Teach
Python's for ... in loops iterate through every element in a list. The loop variable takes on the value of each element in sequence.
Basic Syntax
for element in list:
# do something with element
Teaching Examples
Examples:
def sum_numbers(numbers: list[int]) -> int:
"""calculate sum of all numbers in list"""
total = 0
for number in numbers:
total += number
return total
def test_sum_numbers():
assert sum_numbers([1, 2, 3, 4, 5]) == 15
assert sum_numbers([]) == 0
assert sum_numbers([-1, 1, -2, 2]) == 0
assert sum_numbers([10]) == 10
def count_long_words(words: list[str]) -> int:
"""count words longer than 5 characters"""
count = 0
for word in words:
if len(word) > 5:
count += 1
return count
def test_count_long_words():
assert count_long_words(["hello", "world", "python", "programming"]) == 2
assert count_long_words(["cat", "dog", "bird"]) == 0
assert count_long_words([]) == 0
assert count_long_words(["elephant", "mouse", "rhinoceros"]) == 2
What to Point Out:
- Loop variable (
number,word) represents current element - Loop body executes once for each list element
- Loop variable is automatically updated by Python
- Use descriptive names for loop variables
Common Student Mistakes to Watch For
-
Using index-based loops unnecessarily
# BAD - using indices when not needed
def bad_sum(numbers: list[int]) -> int:
total = 0
for i in range(len(numbers)):
total += numbers[i] # should use `for num in numbers`
return total -
Trying to modify the loop variable
# BAD - trying to change loop variable
def bad_process(numbers: list[int]) -> list[int]:
result = []
for num in numbers:
num = num * 2 # this doesn't affect the original list
result.append(num)
return result -
Confusing element vs index
# BAD - treating element as index
def bad_access(items: list[str]) -> str:
result = ""
for item in items:
result += items[item] # item is the value, not index
return result