Sequence Traversal: Elements, Indices, and Counters
When you process attendance records, sensor readings, or stops on a route, you often repeat an action for entries in a sequence. Sequence Traversal means visiting sequence entries in a chosen order to inspect or process them. The key decision is whether your loop needs each value, each position, or both. The examples here use Python, but that decision applies across programming languages.
Choose what the loop needs
An element-based loop gives you each stored value directly. If your task is to print every name, you can use the value without looking up its position:
names = ["oak", "elm", "ash"]
for name in names:
print(name)On successive iterations, name holds "oak", "elm", and "ash". You do not need a separate counter to retrieve those values.
An index is a position used to access an entry in a sequence. Python uses zero-based indexing: the first entry has index 0. An index-based loop gives you positions, and an expression such as names[i] retrieves the value at position i.
What the task needs | Useful Python pattern | What the loop supplies |
|---|---|---|
Values only | for value in data | Each stored value |
Positions for access or replacement | for i in range(len(data)) | Each valid nonnegative index |
Positions and values together | for i, value in enumerate(data) | An index and its corresponding value |
Keep indices within the valid bounds
For a sequence containing n entries, the valid nonnegative indices satisfy:
The final index is therefore n−1, provided the sequence is not empty. Python's len(data) supplies n, while range(n) produces the integers from 0 through n - 1.
for i in range(len(names)):
print(i, names[i])The loop retrieves each name using its index. The exclusive stop in range makes len(names) a suitable boundary, even though it is not a valid index.
You can also choose a subset of positions. For example, range(0, len(data), 2) visits every second entry, beginning at index 0. The third argument controls the step between successive indices.
For an empty sequence, range(len(data)) produces no indices, so the loop body does not run.
Separate stored positions from display numbers
Python's enumerate supplies a counter and a value together. Its default counter starts at 0, so it matches the stored index during an ordinary forward traversal:
for i, name in enumerate(names):
print(i, name)For a human-facing numbered list, you might instead write:
for number, name in enumerate(names, start=1):
print(number, name)Here, the first name receives display number 1, but its stored index remains 0. Changing the counter's starting value does not change sequence indices. If you need both, keep the stored index and calculate the display number as i + 1.
Also distinguish reading a value from replacing an entry. With numeric entries, assigning a new number to an element-based loop variable does not write that number back into the sequence. To replace an entry, assign through its index, such as data[i] = data[i] + 1.
When tracing a loop, record the current index or counter, the value read, and any changes made by the body. Count completed iterations rather than guessing from the final counter. Assume the sequence's length stays fixed unless the problem explicitly says otherwise.
What to remember
- Traverse values directly when positions are unnecessary.
- For n entries, valid nonnegative indices run from 0 through n−1.
- A range stop value is excluded.
- An enumerate counter can be a display number rather than a stored index.
- Replacing an entry requires an assignment to the sequence itself.
Example: Flagging Greenhouse Readings
Example: A greenhouse controller stores four temperature readings, in degrees Celsius, as readings = [17, 24, 21, 26]. A reading requires an alert when it is at least 24 °C. The stored order stays fixed throughout the problem. A display number is the human-facing number printed beside an entry; this report numbers readings beginning at 1.
Complete each part before revealing its solution.
a) Use an element-based traversal to count the readings requiring an alert. State the count.
The task needs temperature values, so the loop can retrieve each value directly. Start the counter at zero and increase it only when the temperature meets the threshold.
count = 0
for temperature in readings:
if temperature >= 24:
count = count + 1For the first reading, the test 17 >= 24 is ________, so the count remains zero. The second reading is 24 °C, which meets the inclusive threshold, so the count becomes ________. The third reading, 21 °C, does not change it. The final reading, 26 °C, increases it once more.
The final answer is 2 readings requiring an alert.
b) Use an index-based traversal to print the zero-based indices of all readings requiring an alert. State those indices.
The sequence contains ________ entries. Its valid nonnegative indices are therefore 0, 1, 2, and 3. Use each index to retrieve the corresponding temperature.
for i in range(len(readings)):
if readings[i] >= 24:
print(i)At index 0, the temperature is 17 °C, so nothing is printed. At index 1, it is 24 °C, so the loop prints 1. Index 2 contains 21 °C and produces no output. Index 3 contains 26 °C, so the loop prints 3.
The final answer is indices 1 and 3. These are stored positions, rather than temperature values or display numbers.
c) Use enumerate to print each alert's display number and temperature. Begin display numbering at 1, and state the output pairs with temperature units.
Use enumerate(readings, start=1) because the report needs a display number and a value together. The starting counter changes the report numbering, not the stored indices.
for number, temperature in enumerate(readings, start=1):
if temperature >= 24:
print(number, temperature)The first iteration pairs display number 1 with 17 °C, which fails the threshold test. The second pairs number 2 with 24 °C and prints that pair. The third pairs number 3 with 21 °C and prints nothing. The fourth pairs number 4 with 26 °C and prints that pair.
The final output pairs are display number 2 with 24 °C and display number 4 with 26 °C. The code prints the numeric pairs 2 24 and 4 26; the stored temperatures are measured in degrees Celsius.
A library uses Python 3 to label returned books consecutively beginning at 100. Complete the template using a built-in function and its keyword parameter, without adding arithmetic inside the loop.
Replace FUNCTION with and KEYWORD with .
books = ["Atlas", "Field Guide", "Poems"]
for label, title in FUNCTION(books, KEYWORD=100):
print(label, title)A stockroom records quantities in packs and prints a numbered report using the Python code below. Complete the table with the index and display number for each iteration. Enter exact integers.
stock = [9, 5, 12]
for index, quantity in enumerate(stock):
display_number = index + 1
print(display_number, quantity)| Iteration | Index | Display number | Quantity (packs) |
| First | 9 | ||
| Second | 5 | ||
| Third | 12 |