How to loop backwards in python?

PythonIterationRange

Python Problem Overview


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.

Python Solutions


Solution 1 - Python

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.

Solution 2 - Python

for x in reversed(whatever):
    do_something()

This works on basically everything that has a defined order, including xrange objects and lists.

Solution 3 - Python

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 - Python

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 - Python

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionsnakileView Question on Stackoverflow
Solution 1 - PythonChinmay KanchiView Answer on Stackoverflow
Solution 2 - PythonhabnabitView Answer on Stackoverflow
Solution 3 - Pythonchocolate codesView Answer on Stackoverflow
Solution 4 - PythonMichael QinView Answer on Stackoverflow
Solution 5 - Pythonalex.hunterView Answer on Stackoverflow