How to loop backwards in python?
Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Unforgiving Himalayas Looping
--
Chapters
00:00 Question
00:40 Accepted answer (Score 435)
01:24 Answer 2 (Score 245)
01:41 Answer 3 (Score 22)
02:09 Answer 4 (Score 12)
02:21 Thank you
--
Full question
https://stackoverflow.com/questions/3476...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #iteration #range
#avk47
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Unforgiving Himalayas Looping
--
Chapters
00:00 Question
00:40 Accepted answer (Score 435)
01:24 Answer 2 (Score 245)
01:41 Answer 3 (Score 22)
02:09 Answer 4 (Score 12)
02:21 Thank you
--
Full question
https://stackoverflow.com/questions/3476...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #iteration #range
#avk47
ACCEPTED ANSWER
Score 467
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
rangeandxrangefunctions in Python 3, there is justrange, which follows the design of Python 2'sxrange.
ANSWER 2
Score 269
for x in reversed(whatever):
do_something()
This works on basically everything that has a defined order, including xrange objects and lists.
ANSWER 3
Score 12
def reverse(text):
reversed = ''
for i in range(len(text)-1, -1, -1):
reversed += text[i]
return reversed
print("reverse({}): {}".format("abcd", reverse("abcd")))
ANSWER 4
Score 2
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