Traverse a list in reverse order in Python Traverse a list in reverse order in Python python python

Traverse a list in reverse order in Python


Use the built-in reversed() function:

>>> a = ["foo", "bar", "baz"]>>> for i in reversed(a):...     print(i)... bazbarfoo

To also access the original index, use enumerate() on your list before passing it to reversed():

>>> for i, e in reversed(list(enumerate(a))):...     print(i, e)... 2 baz1 bar0 foo

Since enumerate() returns a generator and generators can't be reversed, you need to convert it to a list first.


You can do:

for item in my_list[::-1]:    print item

(Or whatever you want to do in the for loop.)

The [::-1] slice reverses the list in the for loop (but won't actually modify your list "permanently").


It can be done like this:

for i in range(len(collection)-1, -1, -1):    print collection[i]    # print(collection[i]) for python 3. +

So your guess was pretty close :) A little awkward but it's basically saying: start with 1 less than len(collection), keep going until you get to just before -1, by steps of -1.

Fyi, the help function is very useful as it lets you view the docs for something from the Python console, eg:

help(range)


matomo