For loops and range

Topic 2 of 4 in Loops6 min readBeginnerFree course

Overview

A for loop goes through a collection one item at a time and runs a block of code for each. It’s the loop you’ll use most often in Python — for lists, strings, files, ranges of numbers and much more.

Looping over items

Python
fruits = ["apple", "fig", "kiwi"]
for fruit in fruits:
    print(f"I like {fruit}")
Text
I like apple
I like fig
I like kiwi

for loops and range(). In for fruit in [“apple”, “fig”, “kiwi”]: print(fruit), fruit takes each value in turn — “apple” on pass 1, “fig” on pass 2 and “kiwi” on pass 3. range(5) gives 0 1 2 3 4; range(2, 6) gives 2 3 4 5; range(0, 10, 3) gives 0 3 6 9; range(5, 0, -1) gives 5 4 3 2 1. range(start, stop, step): start is the first number (default 0), stop is where it stops — before this number — and step is the jump size (default 1).

On each pass, the loop variable (fruit) is set to the next item, and the block runs. When there are no more items, the loop ends. You choose the variable’s name — make it the singular of the collection: for fruit in fruits, for line in lines, for student in students.

Strings are collections of characters, so they work too:

Python
for letter in "hey":
    print(letter.upper())    # H, E, Y on separate lines

range(): looping over numbers

To repeat something a number of times, or go through a sequence of numbers, use range():

Python
for i in range(5):
    print(i)             # 0 1 2 3 4

range has three forms:

Call Numbers
range(5) 0, 1, 2, 3, 4
range(1, 6) 1, 2, 3, 4, 5
range(0, 20, 5) 0, 5, 10, 15
range(10, 0, -2) 10, 8, 6, 4, 2

Just like slicing, the stop value isn’t included. range(1, 11) gives 1 to 10. That way range(n) gives exactly n numbers.

If you don’t need the number itself, the convention is to name the variable _:

Python
for _ in range(3):
    print("Hip hip hooray!")

enumerate(): positions and items together

Often you need each item’s position too. Beginners write:

Python
for i in range(len(shopping)):
    print(i + 1, shopping[i])

It works, but enumerate() is clearer and less error-prone:

Python
for position, item in enumerate(shopping, start=1):
    print(f"{position}. {item}")

enumerate produces pairs (position, item), which the loop unpacks into two variables. start=1 counts from 1 instead of 0.

Looping over two lists together: zip()

Python
names = ["Asha", "Ben", "Chen"]
scores = [91, 78, 85]
for name, score in zip(names, scores):
    print(f"{name}: {score}")

zip() pairs items up position by position, and stops at the end of the shorter list.

Building results in a loop

Combine a for loop with the counter and accumulator patterns from the previous lesson:

Python
prices = [3.5, 12.0, 7.25]
total = 0
for price in prices:
    total += price
print(total)      # 22.75

The next lessons show more patterns — and some built-in shortcuts like sum(prices).

Nested loops

A loop inside a loop runs the inner loop completely for each pass of the outer one:

Python
for row in range(1, 4):
    for col in range(1, 4):
        print(row * col, end="\t")
    print()
Text
1	2	3
2	4	6
3	6	9

Don’t change a list while looping over it

Removing items from a list while a for loop walks through it skips items in confusing ways:

Python
numbers = [1, 2, 2, 3]
for n in numbers:
    if n == 2:
        numbers.remove(n)    # bug: the second 2 is skipped
print(numbers)               # [1, 2, 3]

Instead, build a new list of the items you want to keep (Loop patterns and Comprehensions show how).

Rule of thumb: use for whenever you’re going through a collection or a known range of numbers; reach for while only when you’re waiting for something to happen.

Exercise

Times tables and a shopping list

(1) Ask for a number and print its times table from 1 to 10 in the form 7 x 3 = 21. (2) Print every even number from 2 to 20 on one line, separated by spaces, using range with a step. (3) Given a shopping list, print each item numbered from 1 (1. eggs), and finally count how many items have more than 4 letters.

Python
# 1. Times table
n = int(input("Times table for: "))

# 2. Even numbers 2..20 on one line

# 3. Numbered shopping list + count of long items
shopping = ["eggs", "bread", "milk", "tomatoes", "tea"]

Summary

  • for item in collection: runs the block once for each item, with item set to that item.
  • range(stop), range(start, stop) and range(start, stop, step) produce numbers; stop is never included.
  • for i in range(5) repeats five times, with i = 0, 1, 2, 3, 4.
  • enumerate(items, start=1) gives positions and items together — no need for range(len(...)).
  • Don’t add or remove items in a list while looping over it; build a new list instead.