Loop Backwards

bruno at modulix onurb at xiludom.gro
Tue Feb 14 04:08:03 EST 2006


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.

for item in reversed(alist):
  do_something_with(item)

or (more perlish at first sight):

for item in alist[::-1]:
  do_something_with(item)



-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'onurb at xiludom.gro'.split('@')])"



More information about the Python-list mailing list