Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to loop backwards in python? [duplicate]

People also ask

Can you loop backwards in Python?

To reverse for loop in Python just need to read the last element first and then the last but one and so on till the element is at index 0. You can do it with the range function, List Comprehension, or reversed() function.

How do you repeat a loop again in Python?

The most common way to repeat a specific task or operation N times is by using the for loop in programming. We can iterate the code lines N times using the for loop with the range() function in Python.

How do you reverse a list in a for loop Python?

Python comes with a number of methods and functions that allow you to reverse a list, either directly or by iterating over the list object. You'll learn how to reverse a Python list by using the reversed() function, the . reverse() method, list indexing, for loops, list comprehensions, and the slice method.


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.


for x in reversed(whatever):
    do_something()

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


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

def reverse(text):
    reversed = ''
    for i in range(len(text)-1, -1, -1):
        reversed += text[i]
    return reversed

print("reverse({}): {}".format("abcd", reverse("abcd")))

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