The Python Oracle

How to loop backwards in python?

--------------------------------------------------
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzle Game 2 Looping

--

Chapters
00:00 How To Loop Backwards In Python?
00:37 Answer 1 Score 269
00:50 Accepted Answer Score 467
01:23 Answer 3 Score 2
01:42 Answer 4 Score 12
01:48 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 range and xrange functions in Python 3, there is just range, which follows the design of Python 2's xrange.




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