Making Decisions and Repeating Work

Loops Over Lists


Learning Objectives

  • You can write a for loop that processes each item of a list.
  • You can trace a loop step by step using a table.
  • You can predict the number of iterations a loop will run.
  • You can explain why modifying a list while iterating over it is risky.

In the previous chapter, you learned how to put many values into a list. The natural next question is: how do you do something with each of them?

The answer in Python is the for loop. It is the most useful tool in this part of the course.

The For-Each Pattern

A for loop walks through a list and runs the same block of code once for each item.

subjects = ["Math", "Physics", "Linear Algebra"]
for subject in subjects:
print(f"Studying {subject}.")

This prints three lines:

Studying Math.
Studying Physics.
Studying Linear Algebra.

Read the first line of the loop out loud: “for each subject in subjects”. That is exactly what Python does. The word subject is a new variable, often called the loop variable. On each iteration, it gets the next value from the list.

The body of the loop — the indented lines underneath — is what runs each time.

Printing in a loop

0 / 5 points

Drag and drop the blocks to build a natural-language program that creates a list containing the first three alphabets. Then, the program should go over each letter in the list using a loop. Inside the loop, the program should print the letters.

The indentation rules are the same as for if statements: four spaces, consistent within the block, marking the lines that belong to the loop.

Print study lines

0 / 10 points

The starter has this list:

subjects = ["Art", "Math", "History"]

Do not ask the user for input in this exercise.

Use a for loop to print one line for each subject in this exact format: Review: <subject>.

Example input:

(no input)

Required output text:

Review: Art
Review: Math
Review: History

Tracing a Loop

Tracing a loop works the same way as tracing any other code, but you make a row for each iteration. Here is a trace of the program above:

Iterationsubject isOutput
1"Math"Studying Math.
2"Physics"Studying Physics.
3"Linear Algebra"Studying Linear Algebra.

That is the whole thing. The loop variable changes on each iteration, the body runs once with that value, and then Python moves on to the next item.

A useful question to ask when reading any loop: how many times will the body run? For for item in collection, the answer is exactly len(collection) times — once per item, no more and no less.

Loops Do Nothing If the List Is Empty

Suppose subjects is the empty list []. How many times does the body of for subject in subjects: run?

Zero times.

subjects = []
for subject in subjects:
print(f"Studying {subject}.")
print("Done.")

This prints only Done. The loop body is skipped entirely because there are no items to iterate over.

This is one of the most useful properties of for loops, and one of the most overlooked. It means that programs handling a list naturally do the right thing on an empty list: nothing. You do not need a special if len(subjects) > 0: guard around the loop just to avoid an error.

It also means that any work you want to do after the loop runs whether or not the list had items. This is exactly where students often forget the empty case. If you compute a total inside the loop and then divide by the number of items, dividing by zero is what bites you, not the loop itself.

You will return to this case explicitly in Verifying Behavior and Finding the Edge Cases AI Misses.

Empty list loop

0 / 5 points

How many times does the body run in for item in []:?


Loops Over Strings Work Too

A string is a sequence of characters, just like a list is a sequence of items. The same for loop works on strings as well as lists:

for letter in "Math":
print(letter)

This prints M, a, t, h on four separate lines. The loop visits each character in order.

You will not need this often, but it is worth knowing because it reinforces the bigger idea: for loops work on any ordered collection. Lists and strings are two examples. Later in the course you will meet others.

Combining a Loop with an if

Often you want the loop body to do something different on different items. That is what if is for, exactly as in Conditionals. The two ideas combine naturally:

minutes_list = [10, 45, 90, 20, 75]
for minutes in minutes_list:
if minutes >= 60:
print(f"{minutes} min -- long session.")
else:
print(f"{minutes} min -- shorter session.")

This prints:

10 min -- shorter session.
45 min -- shorter session.
90 min -- long session.
20 min -- shorter session.
75 min -- long session.

The loop visits each item; the if decides which message to print for that item. Both pieces of indentation matter: the if/else is indented to be inside the loop, and the print lines are indented further to be inside their respective branches.

Label long sessions

0 / 10 points

The program starter comes with this list:

minutes_list = [15, 16, 45, 46, 75]

Do not ask the user for input in this exercise.

Use a loop to iterate over the list with if, elif, and else inside it. For each number, print one line:

  • <minutes> minutes: short when the value is 15 or less
  • <minutes> minutes: medium when the value is between 16 and 45
  • <minutes> minutes: long when the value is 46 or more

Example input:

(no input)

Required output text:

15 minutes: short
16 minutes: medium
45 minutes: medium
46 minutes: long
75 minutes: long

The loop works also without the else:

minutes_list = [10, 45, 90, 20, 75]
for minutes in minutes_list:
if minutes >= 60:
print(f"{minutes} min -- long session.")

This prints only the long sessions:

90 min -- long session.
75 min -- long session.

Conditional printing in a loop

0 / 5 points

Drag and drop the blocks to build a natural-language program that creates a list of numbers. Then, the program should go over each number in the list using a loop. Inside the loop, the program should print the number if the number is greater than 3.

Don’t Modify a List While Iterating Over It

One common mistake is to change a list while a for loop is walking through it.

minutes_list = [10, 45, 90, 20, 75]
for minutes in minutes_list:
if minutes < 30:
minutes_list.remove(minutes)

This looks like it should remove all the short sessions, but the actual behavior is surprising and depends on details you do not need to know yet. Sometimes items get skipped. Sometimes the wrong ones get removed.

The reason is that for walks the list by position, and removing items shifts everything after them. The fix is not to learn the exact rules. The fix is to not do this. If you want to build a filtered version of a list, build a new list:

minutes_list = [10, 45, 90, 20, 75]
long_sessions = []
for minutes in minutes_list:
if minutes >= 30:
long_sessions.append(minutes)
print(long_sessions)

This prints [45, 90, 75]. The original list is untouched, and the new list contains only the items you wanted to keep. This is a pattern you will see often, called filtering.

Check Your Understanding

  1. How many times does this loop body run?
for x in [10, 20, 30, 40, 50]:
print(x)
  1. How many times does this loop body run?
for x in []:
print(x)
  1. Why is it risky to remove items from a list inside a for loop that iterates over the same list?

AI Study Aid

Create a chapter diagram

We're looking into to what extent AI-generated diagrams could help with studying.

Use this study aid to generate an AI-generated visual summary of the material you just studied. Each diagram style emphasizes the content in a different way, so you can choose the focus that feels most useful.

Using the diagram generator is voluntary and does not affect your course progress. We encourage you to try it out and see if it helps, but it's totally up to you! Your answers help us understand how to make better study aids in the future.

Diagrams tried: 0