Count Controlled Iteration (For Loops)
Index-based iteration means using a for loop to visit every position in a data structure in turn, instead of visiting the items directly. The loop variable holds an index (a position number), and you use that index to reach the item, for example word[i] for a string.
The len() function returns the number of items a data structure holds, so len("volcano") is 7 because the string holds seven characters. Indexes start at 0, so those seven characters sit at positions 0, 1, 2, 3, 4, 5 and 6. Writing range(len(word)) starts at 0 and stops before 7, giving exactly 0 to 6: every valid index and nothing beyond. Using range(len(word) + 1) would run one step too far and ask for position 7, which does not exist, so the program would crash with an index error.
word = "volcano"
# i takes each index from 0 up to len(word) - 1
for i in range(len(word)):
print(str(i + 1) + ". " + word[i])Output:
1. v
2. o
3. l
4. c
5. a
6. n
7. o
Because the loop now knows the position, the output can show each character with its position number, which direct iteration cannot do. Building the range from len() also means the loop still visits every item if the data is later made longer or shorter, with no numbers to edit by hand.
Choose index-based iteration when the position itself matters: numbering items as you print them, comparing an item with the one before it, or picking out the item at the same position in a second structure. It is also count-controlled, because len() fixes the number of repetitions before the loop starts.
Edexcel GCSE Computer Science · Count Controlled Iteration (For Loops)
Edexcel GCSE Computer Science · Arrays (Lists)
Edexcel GCSE Computer Science · Two-dimensional Arrays (2D Lists)