Tutorial 10/15 LOOPING THROUGH DATA

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.

menu = ["Burger", "Chips", "Soda"]
for item in menu:
# item changes every cycle
print(item)
Pro Tip

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!

Logic Gate

Predict Output

What happens to the numbers in this loop?

nums = [1, 2, 3]
for x in nums:
  print(x * 10)
Level 25: Bronze

Colour Palette

"Loop through 3 colours and print 'I like ' + colour. Start by completing the list."

> bronze_stream_standby
Level 26: Silver

Missing Colon

"This code fails because of a syntax error. Fix the loop declaration to printing 'Code Is Fun'."

> debugger_module_monitoring
Level 27: Gold

Average Machine

Independent Construction Required

  • Create list: nums = [10, 20, 30, 40].
  • Create a total = 0 variable.
  • Loop through nums and add each to total (total = total + x).
  • Calculate avg = total / 4.
  • Print results (Expected: 25.0).
> computation_vector_online