Try range(100,-1,-1), the 3rd argument being the increment to use (documented here).

("range" options, start, stop, step are documented here)

Answer from 0x6adb015 on Stack Overflow
🌐
GeeksforGeeks
geeksforgeeks.org › python › backward-iteration-in-python
Backward iteration in Python - GeeksforGeeks
July 11, 2025 - a = [10, 20, 30, 40, 50] #Loop through the list #using reversed() to reverse the order of list for b in reversed(a): print(b) ... Let's explore more methods that helps to iterate backward on any iterable. Here are some common approaches: ... range function is provided with three arguments(N, -1, -1). Use this method when we need to modify elements or access their indices. ... s = "Python" # - len(s) - 1: Start at the last index # - -1: Ensures the loop stops after the first character # - -1: The step value to iterate backwards for i in range(len(s) - 1, -1, -1): print(s[i])
Discussions

Why isn't my loop iterating backwards in python?
Hint: Look up documentation on the ‘range’ function…does it actually do what you think it does given the two arguments you provided? Maybe you’re missing an argument? https://docs.python.org/3/library/stdtypes.html#range More on reddit.com
🌐 r/learnprogramming
13
0
March 8, 2023
How to Loop Backwards in Python? - TestMu AI Community
How can I loop backwards from 100 to 0 in Python using a backwards range python? I tried using for i in range(100, 0), but it doesn’t work as expected. How can I fix this to achieve a backward loop? More on community.testmu.ai
🌐 community.testmu.ai
0
December 8, 2024
python - Moving back an iteration in a for loop - Stack Overflow
i = 0 while i < 5: print(i) if ... "moving backwards" i += 1 ... Sign up to request clarification or add additional context in comments. ... Python loop using range are by-design to be different from C/C++/Java for-loops. For every iteration, the i is set the the next value of range(5), no matter what you do to i in between. ... But honestly: I'd step back and think ... More on stackoverflow.com
🌐 stackoverflow.com
How can I loop through an array forward and then backwards and then forwards and... etc with the modulus operator?
Given `n` is 1 less than the length of your array, you can increment and modulus some rotating index `i` against double `n` and then subtract `n`, take the absolute value and you get a bouncing number. It should be noted that you don't need to use any flags as suggested in other comments, but you do lose readability. Explanation: Take your example for an array of length 5, then `n=4`, `i` will rotate through values `[0, 1, 2, 3, 4, 5, 6, 7]` and subtracting `n` from each we get `[-4, -3, -2, -1, 0, 1, 2, 3]`, and the absolute values become `[4, 3, 2, 1, 0, 1, 2, 3]` which you can use to access the values at an index in your array. Try the following code: arr = [1, 2, 3, 4, 5] n = len(arr) - 1 i = n while True: curr_index = abs(i - n) print(arr[curr_index]) i = (i + 1) % (2 * n) and you will get output that looks like: 1 2 3 4 5 4 3 2 1 2 3 4 ... More on reddit.com
🌐 r/learnpython
5
1
September 9, 2021
🌐
Real Python
realpython.com › python-range
Python range(): Represent Numerical Ranges – Real Python
November 24, 2024 - The range parameters start, stop, and step define where the sequence begins, ends, and the interval between numbers. Ranges can go backward in Python by using a negative step value and reversed by using reversed().
🌐
Spark By {Examples}
sparkbyexamples.com › home › python › python for loop in backwards
Python For Loop in Backwards - Spark By {Examples}
May 31, 2024 - # Get the index and items of list ... # 4 40 # 3 30 # 2 50 # 1 20 # 0 10 · In this article, I will explain using reversed() and range() functions of Python how we can implement the loop from the backward direction with ...
🌐
TestMu AI Community
community.testmu.ai › ask a question
How to Loop Backwards in Python? - TestMu AI Community
December 8, 2024 - How can I loop backwards from 100 to 0 in Python using a backwards range python? I tried using for i in range(100, 0), but it doesn’t work as expected. How can I fix this to achieve a backward loop?
Find elsewhere
🌐
Replit
replit.com › home › discover › how to iterate backwards in python
How to iterate backwards in Python | Replit
3 weeks ago - for i in range(10, 0, -2): print(i, end=' ')--OUTPUT--10 8 6 4 2 · You can also iterate backward by giving the range() function a negative step value. This third argument tells the loop to count down instead of up.
🌐
Python Morsels
pythonmorsels.com › looping-in-reverse
Looping in reverse - Python Morsels
May 27, 2025 - To loop in the reverse direction, you can use Python's built-in reversed function: >>> colors = ["purple", "blue", "green", "pink", "red"] >>> for color in reversed(colors): ... print("I like", color) ...
🌐
Towards Data Science
towardsdatascience.com › home › latest › how to reverse python lists more efficiently
How To Reverse Python Lists More Efficiently | Towards Data Science
January 20, 2025 - >>> my_lst = [10, 0, 30, 25, 40, 100, 80] >>> my_lst_reverse_iter = reversed(my_lst) >>> my_lst_reverse_iter <list_reverseiterator object at 0x10afcae20> As you can see, the reversed() function returned an Iterator we can loop over it: >>> for ...
🌐
TutorialsPoint
tutorialspoint.com › backward-iteration-in-python
Backward iteration in Python
August 7, 2019 - In the below example we start at ... above code gives us the following result − ... This method involves slicing the list which starts from the position -1 and go backwards till the first position....
🌐
Reddit
reddit.com › r/learnpython › how can i loop through an array forward and then backwards and then forwards and... etc with the modulus operator?
r/learnpython on Reddit: How can I loop through an array forward and then backwards and then forwards and... etc with the modulus operator?
September 9, 2021 -

Say I have an array:

arr = [1,2,3,4,5]

and I want to output this using a simple counter and the modulus operator

1 
2
3
4 
5 
4
3 
2
1 
2 
3 
4 
5 
... 

Is this possible? I know that you can loop through an array and start over at the beginning by doing

arr[count % len(arr)]

but how do I just switch directions instead of going back to the beginning?

🌐
Plain English
python.plainenglish.io › how-to-loop-backwards-in-python-9724c25e8050
How to Loop Backwards in Python. Looping through a list backwards is… | by Fatos Morina | Python in Plain English
October 7, 2021 - How to Loop Backwards in Python Looping through a list in Python is quite straightforward. Let us mention two ways that you can do it. You can do it using indexes and the length of the list, like the …
🌐
Delft Stack
delftstack.com › home › howto › python › loop backwards in python
How to Loop Backward Iteration in Python | Delft Stack
March 11, 2025 - In this example, the range(10, ... to 1. The first parameter specifies the starting point, the second parameter indicates the stopping point (not inclusive), and the third parameter defines the step, which is negative in this case...
🌐
Stack Abuse
stackabuse.com › bytes › traversing-a-list-in-reverse-order-in-python
Traversing a List in Reverse Order in Python
August 30, 2023 - The range() function can take three parameters - start, stop, and step. By setting the start parameter to the last index of the list, the stop parameter to -1 (to go all the way to the beginning of the list), and the step parameter to -1 (to go backwards), we can traverse the list in reverse order.
🌐
Delft Stack
delftstack.com › home › howto › python › python backward range
How to Get Range Backwards in Python | Delft Stack
March 4, 2025 - This method is straightforward and efficient, making it ideal for scenarios where you need to count down in a loop. Another effective way to iterate backwards is by using the reversed() function in combination with a sequence.
Top answer
1 of 1
9

for loops don't go back or forth. They simply take the iterator object for a given iterable object, then repeatedly call the __next__() object until that method raises StopIteration.

For sequence objects, the iterator simply keeps an internal index that's incremented each time __next__ is called to get the next value in the sequence. That internal index is usually not accessible.

So if your specific use case is made easier by 'going back', you'd have to create an iterator object that exposes the index, or otherwise lets you alter what value is going to be produced for the next __next__ call:

class PositionableSequenceIterator:
    def __init__(self, sequence):
        self.seq = sequence
        self._nextpos = None

    @property
    def pos(self):
        pos = self._nextpos
        return 0 if pos is None else pos - 1

    @pos.setter
    def pos(self, newpos):
        if not 0 <= newpos < len(self.seq):
            raise IndexError(newpos)
        self._nextpos = newpos

    def __iter__(self):
        return self

    def __next__(self):
        try:
            return self.seq[self.nextpos or 0]
        except IndexError:
            raise StopIteration
        finally:
            self.nextpos += 1

so now you can do

iterator = PositionableSequenceIterator(some_list)
for elem in iterator:
    if somecondition:
        iterator.pos -= 2
    # ...

to skip back two steps.

I'd not expect this to be faster than a while loop, however. while loops are not specifically faster, testing the while condition each iteration is not much different from calling iterator.__next__(), really. In your timed test, the while condition is slower because it executes Python bytecode each iteration (both for the condition and to increment n in the loop body), but the range() iterator is implemented entirely in C. The iterator class above implements __next__ in Python code again, so will be just as slow.

To demonstrate, I can show you that the timing differences are entirely due to the condition and loop body being slower:

>>> import timeit
>>> count, total = timeit.Timer("n = 0\nwhile n < 10 ** 6:\n    n += 1").autorange()
>>> whileloop = total / count
>>> count, total = timeit.Timer("for i in range(10 ** 6):\n    pass").autorange()
>>> forloop = total / count
>>> count, total = timeit.Timer("n < 10 ** 6", "n = 10 ** 5 * 5").autorange()
>>> testbelow = total / count
>>> count, total = timeit.Timer("n += 1", "n = 0").autorange()
>>> increment = total / count
>>> count, total = timeit.Timer("nxt()", "nxt = iter(range(1 << 23)).__next__").autorange()  # enough room to find a good test range
>>> rangeitnext = total / count
>>> whileloop - forloop  # the for loop "speed advantage", per million iterations
0.03363728789991001
>>> (testbelow + increment) - rangeitnext  # relative difference per iteration
-9.191804809961469e-08
>>> ((testbelow + increment) - rangeitnext) * 10 ** 9  # microseconds
-91.9180480996147

So in these tests I can at best prove that there's only 92 microseconds between each loop iteration step, with while faster, if that makes any sense. That's because if I repeat this often enough, it'll about hit the (whileloop - forloop) / 10 ** 6 difference, because these numbers are just way too small to really care about.

Note that an iterator like the above is usually overkill. The vast majority of problems where someone might wish to "rewind" an iterator really just want to keep track of previously seen items. You can trivially do that with other options too, like a queue:

from collections import deque

preceding = deque(maxlen=2)
for item in iterable:
    if condition:
        # process items in preceding

    preceding.append(item)

The above keeps the last two items seen around in case you need to process those.

Or you could use zip() and independent iterators:

from itertools import islice

twoforward = islice(iterable, 2, None)
for twoback, current in zip(iterable, twoforward):
    # twoback and current are paired up at indices i - 2 and i.

As for your euler_differentiate_mod() function, the following achieves the same work, without the need to advance a while counter. Your function basically calculates deltas up to 3 times per iteration, and moves to the next iteration when you either have a maximum change within toleration bounds or you tried 3 times:

def euler_differentiate_mod(
    w, bounds=None, delta=1e-3, itern=1000, tols=(10, 0.1), step_mults=(0.1, 10)
):
    if bounds is None:
        bounds = [0] * len(w)

    for _ in range(itern):
        for _ in range(3):
            deltas = [f(delta, *bounds) for f in w]
            maxchange = max(map(abs, deltas[1:]))  # ignore the first delta
            bounds[:] = [b + d for b, d in zip(bounds, deltas)]

            if delta > 1:
                delta *= step_mults[0] / maxchange

            if tols[1] <= maxchange <= tols[0]:
                break

            if delta > 1:
                if tols[0] < maxchange:
                    delta *= step_mults[0] / maxchange
                elif maxchange < tols[1]:
                    delta *= step_mults[1] / maxchange