DSA Traversing Arrays
Traversing an array means visiting each cell once in a chosen order. Forward, backward, and neighbour-pair walks are the three orders this lesson practises.
Walking forward
The loop visits index 0 first and the last index last. Each line prints the index beside its value.
temps = [18, 21, 19, 23]
for i in range(len(temps)):
print(i, temps[i])Walking backward
The range starts at the last index and steps down to 0. The same four values appear in reverse order.
temps = [18, 21, 19, 23]
for i in range(len(temps) - 1, -1, -1):
print(i, temps[i])Neighbour pairs
A neighbour pair is two cells side by side. The loop stops one index early, so the second cell of each pair always exists.
temps = [18, 21, 19, 23]
for i in range(len(temps) - 1):
print(temps[i], temps[i + 1])Example
temps = [18, 21, 19, 23, 25, 22]
for i in range(1, len(temps)):
change = temps[i] - temps[i - 1]
print("Day", i + 1, "change:", change)Key points
- A traversal visits every cell exactly once in a chosen order
- A forward walk uses indices from 0 up to the last index
- A backward walk uses indices from the last index down to 0
- A pair walk runs one index shorter than the list
In this example, a pair walk compares each day with the day before it. The loop starts at index 1, because day one has no earlier day. Each pass subtracts the previous temperature from the current one. A positive change means the day warmed up, and a negative change means it cooled down. Five changes print for the six days, one per pair.
Note
range(len(temps) - 1) ends at the second-to-last index, which keeps temps[i + 1] inside the list.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท Python Playground
Exercise
How many neighbour pairs does a list of 6 values have?