Feed on
Posts
Comments

to iterate over a list in reverse order in python, i use the ‘reverse’ method. i’m sure there are faster ways to do this in terms of running time, but its hard to conceive of anything easier to implement.

here goes: to iterate over ‘my_list’ backwards, write:

my_list.reverse()
for item in my_list:
print item


Bookmark and Share

if that was helpful ...

check out the other tips and tricks i've compiled on these pages. you might learn something else interesting!

5 Responses to “read a list backwards in python”

  1. on 14 Jun 2007 at 12:02 am Henry

    for i in reversed(my_list):
    print i

    (new builtin from python 2.4)

  2. on 01 Oct 2007 at 2:12 pm Eric Brunson

    Just to show there’s more than one way to do it:

    for i in list[::-1]:
    print i

    :-)

  3. on 24 Jul 2008 at 8:42 pm Zach Dwiel

    correct me if I am wrong, but reversed is the way to go if memory is an issue as the other two solutions first create a copy of the list while rereversed(list) simply returns a reverse iterator?

  4. on 11 Feb 2011 at 10:38 am Paul Man

    If you need the index or the sequence is a string you can always:

    for i in range(len(my_list) – 1, -1, -1):
    print my_list[i]

  5. on 06 Jul 2011 at 4:01 pm paul.reverse

    I would like to emphasize that Zach Dwiel’s solution is side effect free, which he also states.

    In the original solution, if you wanted to print out the list and then process the list again with the original order, then you would need:

    list.reverse()

    # print list in reverse order
    for i in list:
    print i

    list.reverse()

    # print list in original order
    for i in list:
    print i

    where as Zach’s solution allows for the more optimal

    for i in reversed(list):
    print i

    for i in list:
    print i

Did I get this wrong? Let me know!

Trackback URI | Comments RSS

More blogs about http://desk.stinkpot.org:8080/tricks.