Loop Backwards

bonono at gmail.com bonono at gmail.com
Mon Feb 13 21:38:18 EST 2006


mensanator at aol.com wrote:
> Dave wrote:
> > This should be simple, but I can't get it:
> >
> > How do you loop backwards through a list?
> >
> > For example, in, say, Javascript:
> >
> > for (var i  = list.length - 1; i >=0; i--) {
> >     do_stuff()
> > }
> >
> > I mean, I could reverse the list, but I don't want to. I want it to
> > stay exactly the same, but I want to start at the end and end at the
> > beginning.
>
> Negative indexes start at the opposite end than positive indexes.
>
> >>> s = [1,2,3,4,5]
> >>> for i in range(len(s)):
> 	print s[-i-1],
>
> 5 4 3 2 1
I thought the python way is to use slice :

range(10)[::-1]




More information about the Python-list mailing list