SoFunction
Updated on 2024-11-10

Three inverse order traversal operations for python lists and strings

Inverse order traversal of lists

a = [1,3,6,8,9]
print("Iterating through subscripts in reverse order 1:")
for i in a[::-1]:
    print(i, end=" ")
print("\n traverses 2 in reverse order by subscripts:")
for i in range(len(a)-1,-1,-1):
    print(a[i], end=" ")
print("\n traversed in reverse order by reversed:")
for i in reversed(a):
    print(i, end=" ")

exports

Iterate through 1 in reverse order by subscripts:
9 8 6 3 1
Iterate through 2 in reverse order by subscripting:
9 8 6 3 1
Iterate in reverse order by reversed:
9 8 6 3 1

The inverse order traversal of a string is the same as for a list.

python traverses the list from back to front

It is convenient to traverse an array from back to front in C, e.g.:

for(int i = 5; i >= 0; i--){
    printf("%d\n", i);
}

But in python the default is to traverse the list from back to front, sometimes you need to traverse from back to front. According to the usage of the range function:

range(start, end[, step])

The method for traversing a list from back to front in python is:

lists = [0, 1, 2, 3, 4, 5]
# Output 5, 4, 3, 2, 1, 0
for i in range(5, -1, -1):
    print(lists[i])
 
# Outputs 5, 4, 3
for i in range(5, 2, -1):
    print(lists[i])

The above is a personal experience, I hope it can give you a reference, and I hope you can support me more.