Python Tutorial · Control Flow · Lesson 22 of 42

Python For Loops

Loop over lists, strings, ranges and dictionaries with enumerate() and zip().

Looping over items

A for loop goes through each item of any iterable — list, string, tuple, dict, set or file.

Example 1Try it yourself
for fruit in ["apple", "banana", "cherry"]:
    print(fruit)
for letter in "hey":
    print(letter)

Output

apple
banana
cherry
h
e
y

range()

range(stop), range(start, stop) and range(start, stop, step) produce sequences of numbers (stop not included).

Example 2Try it yourself
print(list(range(5)))
print(list(range(2, 6)))
print(list(range(10, 0, -3)))
total = 0
for i in range(1, 101):
    total += i
print(total)

Output

[0, 1, 2, 3, 4]
[2, 3, 4, 5]
[10, 7, 4, 1]
5050

enumerate() and zip()

Need the index too? Use enumerate(). Looping over two lists side by side? Use zip().

Example 3Try it yourself
names = ["Ana", "Bo", "Cy"]
scores = [90, 85, 77]
for i, name in enumerate(names, start=1):
    print(i, name)
for name, score in zip(names, scores):
    print(f"{name}: {score}")

Output

1 Ana
2 Bo
3 Cy
Ana: 90
Bo: 85
Cy: 77

Nested loops

Example 4Try it yourself
for row in range(1, 4):
    line = ""
    for col in range(1, 4):
        line += f"{row * col:4}"
    print(line)

Output

   1   2   3
   2   4   6
   3   6   9

Test yourself

What does list(range(1, 4)) produce?

  1. [1, 2, 3, 4]
  2. [1, 2, 3]
  3. [0, 1, 2, 3]
  4. [1, 4]
Show answer

Answer: [1, 2, 3]