All lessons

Lists & loops · step 13 of 22

For loops

10 minDo something once for every item — the pattern behind almost everything.

For every item

A for loop runs its block once per item in a sequence.

colors = ["red", "green", "blue"]
for color in colors:
    print(color)

color is the loop variable: it holds the current item on each trip around. Name it for one thing — for student in students reads far better than for x in students.

Counting with range()

for number in range(5):
    print(number)      # 0 1 2 3 4 — range stops before the end

for number in range(1, 4):
    print(number)      # 1 2 3 — start, then stop before 4

Building a total

This pattern shows up everywhere:

prices = [2.5, 3, 4.25]
total = 0
for price in prices:
    total = total + price
print(total)     # 9.75

Start the total at 0, add each item inside the loop, and print after the loop finishes. Indentation is what tells Python which lines are inside the loop.

Remember this

  • for runs the block once per item
  • range(5) counts 0 to 4
  • Indented lines under the for are the repeated ones

Quick quiz

Three questions. 3 correct answers and you have the idea — you can retry as often as you like.

  1. 1. What does range(3) produce?

  2. 2. How many times does `for x in [2, 4, 6]:` run its block?

  3. 3. Where does the line that adds a price to the total belong?

Answer all three to check them.

Now write it yourself

0/3 passed
1

Practice 1

The list `numbers` is ready. Print each number doubled, one per line.

practice_1.py

Given for you

numbers = [4, 8, 15, 16]
2

Practice 2

The list `prices` is ready. Add every price together and print the total.

practice_2.py

Given for you

prices = [2.5, 3, 4.25]
3

Practice 3

Print the numbers 1 to 5 — one per line — using range().

practice_3.py

Finish with two of three quiz answers correct and every exercise passing, and this lesson is marked complete.