Can a for loop iterate over a list backwards?


#1

Question

Is it possible to have a for loop iterate over a list in reverse order without changing the list?

Answer

Yes, you can iterate over a list in reverse order without changing the list using the reversed() function. In this code, the list is printed in backward order but after the for loop, the final print() shows that the original list is unchanged.

mylist = [ 1, 2, 3, 4, 5, 6, 7]

for val in reversed(mylist):
    print(val)

print(mylist)