How to loop backwards in python?
Solution 1
range()
and xrange()
take a third parameter that specifies a step. So you can do the following.
range(10, 0, -1)
Which gives
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
But for iteration, you should really be using xrange
instead. So,
xrange(10, 0, -1)
Note for Python 3 users: There are no separate
range
andxrange
functions in Python 3, there is justrange
, which follows the design of Python 2'sxrange
.
Solution 2
for x in reversed(whatever):
do_something()
This works on basically everything that has a defined order, including xrange
objects and lists.
Solution 3
All of these three solutions give the same results if the input is a string:
1.
def reverse(text):
result = ""
for i in range(len(text),0,-1):
result += text[i-1]
return (result)
2.
text[::-1]
3.
"".join(reversed(text))
Solution 4
def reverse(text):
reversed = ''
for i in range(len(text)-1, -1, -1):
reversed += text[i]
return reversed
print("reverse({}): {}".format("abcd", reverse("abcd")))
Solution 5
To reverse a string without using reversed
or [::-1]
, try something like:
def reverse(text):
# Container for reversed string
txet=""
# store the length of the string to be reversed
# account for indexes starting at 0
length = len(text)-1
# loop through the string in reverse and append each character
# deprecate the length index
while length>=0:
txet += "%s"%text[length]
length-=1
return txet
Related videos on Youtube
snakile
Updated on September 18, 2020Comments
-
snakile over 3 years
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, usingwhile
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.
-
Parthik B. over 4 yearsa little too late to answer but, I didn't see the easiest solution here so here it is..........................................................
for i in range(n)[::-1]
this will give youi
in reverse order. Peace out. -
BigDreamz over 3 years@ParthikB wouldn't the reverse in the end create extra space? looks like you are creating a new reversed array - i may be wrong?
-
-
Odomontois almost 14 yearsAware that reversed function is returning a list. So reversed(range(100000)) will return new list with 100000 items.
-
habnabit almost 14 years@Odomontois, no, it doesn't. It returns an iterator.
-
nosklo almost 14 years@Odomontois: Huh, that's false:
print reversed([1, 2, 3])
returns a<listreverseiterator object at 0xb77f1bec>
. -
mzz almost 14 yearsSince this question is about iteration please use xrange instead of range (doesn't matter much for small ranges but starts mattering for large ones).
-
Katriel almost 14 years@mzz -- only in Python 2.x
-
Chinmay Kanchi almost 14 yearsI used
range
simply because the OP did.xrange
vsrange
only matters for really large ranges, like hundreds of megabytes. Also, in Python 3.x, this distinction is gone. -
habnabit almost 14 years@Chinmay, why not use your answer as a way of showing best practices to the OP? No reason not to suggest using
xrange
. -
snakile almost 14 yearsWhat is xrange? Is it the same as range but faster? If so then why is it faster?
-
Chinmay Kanchi almost 14 years
xrange
produces a generator instead of alist
. What this means is that instead of taking up all the memory at the start, the value required is produced at the time when it's required. For more details, see docs.python.org/tutorial/classes.html#generators -
Odomontois almost 14 yearsYes. Sorry. It returns result of obj.__reversed__ method. So by default generator objects haven't this like many others iterables. And even reversed(reversed([1,2,3])) raises TypeError. So you HAVE to create a list before send some iterable to reversed in many situations like reversed([expr(i) for i in iterable if cond(i)]) - without brackets it falls.
-
snakile almost 14 yearsTurns out xrange doesn't exist in python 3...
-
Chinmay Kanchi almost 14 yearsNo, it doesn't. Your question didn't specify which version of python you were using, and the default assumption tends to be python 2.x
-
aks over 8 yearsWhy would you want to do this way? This is rather simple: def reverse(text): new_text = "" for char in text: new_text = char + new_text return new_text
-
Hatim over 8 yearsi think you should use range(10, -1, -1) instead of range(10, 0, -1). because range(10, 0, -1) will stop at the index 0, as a result, the index 0 value will not print.
-
mattst over 7 yearsTo Clarify: In Python 3 the Python 2 xrange() function has been renamed as just range() and there is no function which has the same behaviour as the Python 2 range() function. See: What’s New In Python 3
-
Chris Flesher almost 7 yearsActually you should use range(n-1, -1, -1), this will provide the values between zero and n-1. Both this answer and some of the comments have off-by-one issues.
-
the_raging_deaner over 4 yearsYeah in this example you would use (9,-1,-1)
-
Hassan over 4 years@ChrisFlesher you can simply use
range(n)[::-1]
which is translated torange(n-1, -1, -1)
(tested in python 3.7) -
Ridhwaan Shakeel over 3 yearswhich is the recommended method depending on situation?
-
Jamie Nicholl-Shelley about 3 yearsThis should be the accepted answer imo
-
Urthor about 2 yearsThis is the best answer. Iterating through the values like with a for loop is not what people want every time. Iterating by index is far more flexible.