Traverse a list in reverse order in Python
So I can start from len(collection) and end in collection.
EDIT: Sorry, I forgot to mention I also want to be able to access the loop index.
Use the reversed() built-in function:
>>> a = ["foo", "bar", "baz"] >>> for i in reversed(a): ... print i ... baz bar foo
To also access the original index:
>>> for i, e in reversed(list(enumerate(a))): ... print i, e ... 2 baz 1 bar 0 foo
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").
If you need the loop index, and don't want to traverse the entire list twice, or use extra memory, I'd write a generator.
def reverse_enum(L): for index in reversed(xrange(len(L))): yield index, L[index] L = ['foo', 'bar', 'bas'] for index, item in reverse_enum(L): print index, item
It can be done like this:
for i in range(len(collection)-1, -1, -1): print collection[i]
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:
The reversed builtin function is handy:
for item in reversed(sequence):
The documentation for reversed explains its limitations.
For the cases where I have to walk a sequence in reverse along with the index (e.g. for in-place modifications changing the sequence length), I have this function defined an my codeutil module:
import itertools def reversed_enumerate(sequence): return itertools.izip( reversed(xrange(len(sequence))), reversed(sequence), )
This one avoids creating a copy of the sequence. Obviously, the reversed limitations still apply.
How about without recreating a new list, you can do by indexing:
>>> foo = ['1a','2b','3c','4d'] >>> for i in range(len(foo)): ... print foo[-(i+1)] ... 4d 3c 2b 1a >>>
>>> length = len(foo) >>> for i in range(length): ... print foo[length-i-1] ... 4d 3c 2b 1a >>>
Use list.reverse() and then iterate as you normally would.
The other answers are good, but if you want to do as List comprehension style
collection = ['a','b','c'] [item for item in reversed( collection ) ]
def reverse(spam): k =  for i in spam: k.insert(0,i) return "".join(k)
>>> l = ["a","b","c","d"] >>> l.reverse() >>> l ['d', 'c', 'b', 'a']
>>> print l[::-1] ['d', 'c', 'b', 'a']
the reverse function comes in handy here:
myArray = [1,2,3,4] myArray.reverse() for x in myArray: print x
use built-in function reversed() for sequence object,this method has the effect of all sequences
I like the one-liner generator approach:
((i, sequence[i]) for i in reversed(xrange(len(sequence))))