Python: Iterating Lists
Process every item in a collection one by one.
The Hook
Imagine a teacher taking the register.
She doesn't say "Everyone say 'Here' at once!". She goes through the list, one by one.
This is Iteration. We loop through a list and handle each item individually.
Worked Example
Printing a restaurant menu using a for loop.
Variable Names
Always use a logic link. If the list is nums, use for n in nums. If it is students, use for s in students. It makes your code self-documenting!
Predict Output
What happens to the numbers in this loop?
for x in nums:
print(x * 10)
Colour Palette
"Loop through 3 colours and print 'I like ' + colour. Start by completing the list."
Missing Colon
"This code fails because of a syntax error. Fix the loop declaration to printing 'Code Is Fun'."
Average Machine
Independent Construction Required
- Create list:
nums = [10, 20, 30, 40]. - Create a
total = 0variable. - Loop through
numsand add each to total (total = total + x). - Calculate
avg = total / 4. - Print results (Expected: 25.0).