Traverse a list in reverse order in Python

So I can start from len(collection) and end in collection[0].

EDIT: Sorry, I forgot to mention I also want to be able to access the loop index.

Answers


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:

help(range)


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
>>>

OR

>>> 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.

http://docs.python.org/tutorial/datastructures.html


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']

OR

>>> 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

more detailed reference link


I like the one-liner generator approach:

((i, sequence[i]) for i in reversed(xrange(len(sequence))))

Need Your Help

ANTLR Parser with manual lexer

c# documentation antlr lexer parser-generator

I'm migrating a C#-based programming language compiler from a manual lexer/parser to Antlr.

PostgreSQL index usage, backing up pg_catalog data

postgresql indexing database-backups

I'm currently reviewing the usage of indexes in a complex PostgreSQL database. One of the queries that look useful is this

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.