Run the same block once for every item in a sequence: numbers, list items or characters.
# iterate over range
for i in range(5):
print(i)
# ans: prints 0, 1, 2, 3, 4 (one per line)
Each pass, i takes the next value from range(5); the loop stops when the values run out.
# range(start, stop)
for i in range(2, 7):
print(i)
# ans: 2, 3, 4, 5, 6
# range(start, stop, step)
for i in range(0, 10, 2):
print(i)
# ans: 0, 2, 4, 6, 8
Start at start, add step each time, and stop before reaching stop.
# iterate list items
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
# ans: apple, banana, cherry (one per line)
No index needed: the loop variable is each item itself.
# enumerate for index and value
fruits = ["apple", "banana"]
for i, fruit in enumerate(fruits):
print(i, fruit)
# ans: 0 apple
# ans: 1 banana
# iterate over characters
for char in "abc":
print(char)
# ans: a, b, c (one per line)
Predict the answer, then press โ to trace the loop and check.
# how many iterations?
for i in range(10):
pass
# ans: 10 iterations
# what is i after the loop?
for i in range(3):
pass
# ans: i is 2 (the last value)
# what prints?
for i in range(3, 3):
print(i)
# ans: nothing (empty range)
# negative step?
for i in range(5, 0, -1):
print(i)
# ans: 5, 4, 3, 2, 1
# what is the sum?
total = 0
for i in range(1, 6):
total += i
# ans: 15 (1+2+3+4+5)
# enumerate start?
for i, x in enumerate(['a', 'b'], start=1):
print(i)
# ans: 1, 2
# what is the final i?
for i in range(5):
if i == 3:
pass
# ans: i is 4 (the loop continues)
# nested loop count?
count = 0
for i in range(3):
for j in range(2):
count += 1
# ans: count is 6
# empty list?
for item in []:
print(item)
# ans: nothing (empty list)
# what prints?
for i in range(1, 10, 3):
print(i)
# ans: 1, 4, 7
# modify the loop variable?
for i in range(3):
i = 10
print(i)
# ans: 10, 10, 10
# ans: (it doesn't change the iteration)
range(stop)Counts from 0 up to, but not including, stop.
range(start, stop, step)A negative step counts down; an empty range runs the body zero times.
Lists, strings and enumerate(...) pairs all work in a for.
Keeps its last value after the loop; reassigning it inside does not change what comes next.