How to loop backwards in python?

528,796

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 and xrange functions in Python 3, there is just range, which follows the design of Python 2's xrange.

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
Share:
528,796

Related videos on Youtube

snakile
Author by

snakile

Updated on September 18, 2020

Comments

  • snakile
    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, 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.

    • Parthik B.
      Parthik B. over 4 years
      a 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 you i in reverse order. Peace out.
    • BigDreamz
      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
    Odomontois almost 14 years
    Aware that reversed function is returning a list. So reversed(range(100000)) will return new list with 100000 items.
  • habnabit
    habnabit almost 14 years
    @Odomontois, no, it doesn't. It returns an iterator.
  • nosklo
    nosklo almost 14 years
    @Odomontois: Huh, that's false: print reversed([1, 2, 3]) returns a <listreverseiterator object at 0xb77f1bec>.
  • mzz
    mzz almost 14 years
    Since 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
    Katriel almost 14 years
    @mzz -- only in Python 2.x
  • Chinmay Kanchi
    Chinmay Kanchi almost 14 years
    I used range simply because the OP did. xrange vs range only matters for really large ranges, like hundreds of megabytes. Also, in Python 3.x, this distinction is gone.
  • habnabit
    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
    snakile almost 14 years
    What is xrange? Is it the same as range but faster? If so then why is it faster?
  • Chinmay Kanchi
    Chinmay Kanchi almost 14 years
    xrange produces a generator instead of a list. 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
    Odomontois almost 14 years
    Yes. 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
    snakile almost 14 years
    Turns out xrange doesn't exist in python 3...
  • Chinmay Kanchi
    Chinmay Kanchi almost 14 years
    No, 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
    aks over 8 years
    Why 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
    Hatim over 8 years
    i 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
    mattst over 7 years
    To 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
    Chris Flesher almost 7 years
    Actually 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
    the_raging_deaner over 4 years
    Yeah in this example you would use (9,-1,-1)
  • Hassan
    Hassan over 4 years
    @ChrisFlesher you can simply use range(n)[::-1] which is translated to range(n-1, -1, -1) (tested in python 3.7)
  • Ridhwaan Shakeel
    Ridhwaan Shakeel over 3 years
    which is the recommended method depending on situation?
  • Jamie Nicholl-Shelley
    Jamie Nicholl-Shelley about 3 years
    This should be the accepted answer imo
  • Urthor
    Urthor about 2 years
    This 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.