This question already has an answer here:
- Loop backwards using indices in Python? 12 answers
I'm talking about doing something like:
for(i=n; i>=1; --i) {
//do something with i
}
I can think of some ways to do so in python (creating a list of range(1,n+1)
and reverse it, using while
and --i
, ...) but I wondered if there's a more elegant way to do it. Is there?
EDIT: Some suggested I use xrange() instead of range() since range returns a list while xrange returns an iterator. But in Python 3 (which I happen to use) range() returns an iterator and xrange doesn't exist.
All of these three solutions give the same results if the input is a string:
1.
2.
3.
This works on basically everything that has a defined order, including
xrange
objects and lists.To reverse a string without using
reversed
or[::-1]
, try something like:range()
andxrange()
take a third parameter that specifies a step. So you can do the following.Which gives
But for iteration, you should really be using
xrange
instead. So,