Loop Backwards

skip at pobox.com skip at pobox.com
Mon Feb 13 22:01:22 EST 2006


    Dave> This should be simple, but I can't get it:
    Dave> How do you loop backwards through a list?

Standard idiom:

    for i in range(len(mylist)-1, -1, -1):
        do_stuff()

Contrast that with the standard forward loop:

    for i in range(len(mylist)):
        do_stuff()

So, to go backwards, just add "-1, -1, -1" to the range function in the
forward loop version.

Skip



More information about the Python-list mailing list