Python Loops · Lesson 35 of 149

Python For Loops and range()

What you will learn

  • How a for loop goes through the items of a sequence
  • How to loop over strings, lists, tuples and dictionaries
  • How range() makes sequences of numbers: range(stop), range(start, stop), range(start, stop, step)
  • How the loop variable behaves
  • The trap of changing a list while looping over it

1. The for loop

A for loop repeats a block once for each item of a collection. You do not have to count or update anything yourself:

for ch in "abc":
    print(ch, end=" ")
print()

for n in [10, 20, 30]:
    print(n * 2, end=" ")
print()
a b c 
20 40 60 

The layout is: the word for, a name for the current item, the word in, the collection, a colon, and an indented block. On each pass, Python puts the next item into the name and runs the block. When the items are used up, the loop ends.

Any collection works: a string gives its characters, a list or tuple gives its items, and the items may be of different types:

for x in (1, "two", 3.0):
    print(type(x).__name__, end=" ")
print()
int str float 

A for loop over an empty collection runs zero times.

Quick check: how many times does `for ch in "hello":` run its block?

5 times, once for each character.

2. Looping a number of times: range()

To repeat something a certain number of times, or to go through numbers, use range(). It has three forms:

Form Gives Example Numbers
range(stop) 0 up to, but not including, stop range(5) 0, 1, 2, 3, 4
range(start, stop) start up to, but not including, stop range(2, 6) 2, 3, 4, 5
range(start, stop, step) the same, moving step at a time range(0, 10, 3) 0, 3, 6, 9
print(list(range(5)))
print(list(range(2, 6)))
print(list(range(0, 10, 3)))
print(list(range(5, 0, -1)))
print(list(range(10, 0, -3)))
print(list(range(3, 3)), list(range(5, 2)))
[0, 1, 2, 3, 4]
[2, 3, 4, 5]
[0, 3, 6, 9]
[5, 4, 3, 2, 1]
[10, 7, 4, 1]
[] []
  • The stop value is never included, the same rule as slices (lesson 4.2). So range(5) has exactly 5 numbers.
  • A negative step counts down, and then start must be bigger than stop.
  • If the range cannot move in that direction, it is simply empty.
  • list(...) turns a range into a list so you can see it.
for i in range(1, 4):
    print(i, "squared is", i ** 2)
1 squared is 1
2 squared is 4
3 squared is 9

Doing something n times

When you do not need the number, the convention is to call the loop variable _:

for _ in range(3):
    print("hi", end=" ")
print()
hi hi hi 

range() is lazy

A range does not create all its numbers in memory. It remembers only its start, stop and step, so even a gigantic range is instant. It still supports len, in and indexing:

r = range(2, 20, 3)
print(r, len(r), 8 in r, 9 in r, r[1], r.start, r.stop, r.step)
big = range(10 ** 12)
print(len(big), 5 in big, big[10 ** 11])
range(2, 20, 3) 6 True False 5 2 20 3
1000000000000 True 100000000000

The first line shows a small range: its length, two membership tests, the second item and its three settings. The second line shows a range of a million million numbers, answered instantly.

The arguments must be whole numbers:

range(5.0)
TypeError: 'float' object cannot be interpreted as an integer

A step of 0 is also an error: range(0, 10, 0) raises ValueError: range() arg 3 must not be zero.

3. Looping over dictionaries

Looping over a dictionary gives its keys. Use .values() for the values and .items() for both:

d = {"a": 1, "b": 2}
for key in d:
    print(key, end=" ")
print()
for value in d.values():
    print(value, end=" ")
print()
for key, value in d.items():
    print(key, "=", value, end="; ")
print()
a b 
1 2 
a = 1; b = 2; 

for key, value in d.items() unpacks each pair into two names (lesson 2.1). The same works for any loop over pairs:

for a, b in [(1, 2), (3, 4)]:
    print(a + b, end=" ")
print()
3 7 

Dictionaries are chapter 9; for now you only need this pattern.

4. Looping over positions

If you need the position of each item, you could count with range(len(...)):

words = ["apple", "fig", "kiwi"]
for i in range(len(words)):
    print(i, words[i], end="; ")
print()
0 apple; 1 fig; 2 kiwi; 

This works, but loop over the items directly when you can, and use enumerate (lesson 6.6) when you need both. Looping over items is shorter and cannot go out of range.

5. The loop variable

The loop variable is an ordinary name. A few facts:

  • It keeps its last value after the loop ends.
  • Changing it inside the block does not change the collection, and does not affect the next pass.
for i in range(3):
    pass
print("i after the loop:", i)

for n in range(3):
    n = n * 10
    print(n, end=" ")
print()

mylist = [1, 2]
for item in mylist:
    item += 100
print(mylist)
i after the loop: 2
0 10 20 
[1, 2]

Adding 100 to item changed only the name item: numbers are immutable (lesson 2.6), so the list is untouched. To change items in a list, use their positions, or build a new list (chapter 7).

If the collection is empty, the loop variable is never set, so using it after the loop gives a NameError.

6. The trap: changing a list while looping

Do not add or remove items of a list you are looping over. The loop follows positions, so removing an item moves the others and the loop skips one:

nums = [2, 4, 6, 8]
for n in nums:
    if n % 2 == 0:
        nums.remove(n)
print(nums)
[4, 8]

All four numbers are even, but two stayed. After removing 2, the list shifted, so the loop jumped over 4. There are two safe fixes:

nums = [2, 4, 6, 8]
for n in nums[:]:
    if n % 2 == 0:
        nums.remove(n)
print(nums)

nums = [2, 4, 6, 8, 1]
print([n for n in nums if n % 2 != 0])
[]
[1]

The first loops over a copy (nums[:], lesson 2.7) while changing the original. The second builds a new list with a list comprehension (chapter 12), which is usually the best choice.

Worked example: a multiplication table

Print the table of 7 from 1 to 5.

for i in range(1, 6):
    print(f"7 x {i} = {7 * i}")
7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
7 x 4 = 28
7 x 5 = 35
Part What it does
range(1, 6) gives 1, 2, 3, 4, 5 (6 is not included)
i the current number on each pass
f"7 x {i} = {7 * i}" builds one line with an f-string (lesson 4.5)

To print the total of the table as well, add up 7 * i in a variable inside the loop.

Common mistakes

  • Expecting range(5) to include 5. It stops at 4.
  • Using range(len(x)) when looping over the items is enough.
  • Passing a float to range. Use whole numbers.
  • Changing a list while looping over it. Loop over a copy, or build a new list.
  • Expecting to change a list by changing the loop variable.
  • Using the loop variable after an empty loop.

Key takeaways

  • for item in collection: runs its block once for each item; an empty collection means zero passes.
  • range(stop), range(start, stop) and range(start, stop, step) give whole numbers, never including stop.
  • Looping over a dictionary gives keys; use .values() or .items() for values or pairs.
  • The loop variable keeps its last value, and changing it does not change the collection.
  • Never add or remove items of a list while looping over it; use a copy or build a new list.

Practice

1. What are list(range(4)) and list(range(3, 7))?

Show answer

[0, 1, 2, 3] and [3, 4, 5, 6].

2. Write a loop that prints the even numbers from 2 to 10.

Show answer
for n in range(2, 11, 2):
    print(n)

3. Write a loop that counts down from 5 to 1.

Show answer
for n in range(5, 0, -1):
    print(n)

4. Use a for loop to add up the items of [4, 8, 15] into total.

Show answer
total = 0
for n in [4, 8, 15]:
    total += n

total is 27.

5. Loop over {"x": 1, "y": 2} so that each pass prints x 1, then y 2.

Show answer
for key, value in {"x": 1, "y": 2}.items():
    print(key, value)

6. Why is it risky to remove items from a list inside a for loop over that same list, and what is a safe way?

Show answer

Removing items shifts the positions, so the loop skips items. Loop over a copy (for n in nums[:]:) or build a new list, such as [n for n in nums if keep(n)].