← Back to course
Code Crew G4 / Week 03 / Monday
1/6
Week 03 Β· Loop through a list

Monday

Visit every item
// Visit every item
⏱ about 15 min

Monday: Visit every item

Rocket has a new job: read every crate name over the station speakers. He types print(cargo[0]), then print(cargo[1]), then print(cargo[2]). The cargo list has twenty items.

"This will take all day," he groans.

Raven reads over his shoulder. "What do you notice about your lines?" she asks. "They are all the same," Rocket says. "Only the index changes."

Nova flies in a little circle, around and around. "Would you like a hint? Python can visit each item for you, one after another."

The for loop

A for loop visits each item in a list, one at a time. Read this program.

cargo = ["water", "oats", "tools"]
for item in cargo:
    print(item)
The screen shows
water
oats
tools
Rounditem holdsThe screen shows
1waterwater
2oatsoats
3toolstools
  • The for line ends with a colon.
  • The lines under it are indented with four spaces. They are the loop body.
  • item is a variable. Each round, it holds the next item in the list.
  • You can pick any good name instead of item, like crate or name.
A list has 5 items. A for loop prints each item. How many lines show on the screen?
WHY THIS EXERCISEA for loop runs its body once per item. That is what makes it so useful.
Statement about for loopsTrue or false?
The for line ends with a colon.?
The loop body is indented.?
The loop variable must be called item.?
The loop visits the items from the last one to the first one.?
WHY THIS EXERCISEKnowing the parts of a loop helps you read any loop, however long.
crew = ["Rocket", "Raven", "Kai"]
for name in crew:
    print("Check:", name)
TRACE THE LOOP
  • Read the question.
  • Tap your answer.
Look at the program above. What is the first line on the screen?
What is the last line on the screen?
Try it
Point at each word in this sentence, one at a time.
That is a loop! Your finger is the loop variable.

Practice lab: pack the tools

tools = ["drill", "tape", "clamp", "rope"]
for t in tools:
    print("Pack", t)
What is the first line on the screen?
What is the last line on the screen?
How many lines show in all?
In round 2, what does t hold?
PARTS OF A LOOP
  • Read the question.
  • Tap your answer.
What must the for line end with?
How many spaces indent the loop body?
Which line starts a loop over a list named pods?
Statement about the tools programTrue or false?
In round 1, t holds "drill".?
The loop runs 3 times.?
t holds a new item each round.?
print runs only once in all.?
WHY THIS EXERCISEThe number of rounds always matches the number of items in the list.
A list holds ["a", "b", "c", "d", "e", "f"]. A loop prints each item. How many lines show?
WHY THIS EXERCISEOne item means one round, and one round means one print here.

Awesome! One loop did the work of many lines. Tomorrow you will find out which lines are inside a loop and which are not.