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 OverflowWhy isn't my loop iterating backwards in python?
python - How can I reverse index and -1 each loop - Stack Overflow
Iterate Backwards in Python with Index - TestMu AI Community
loops - Traverse a list in reverse order in Python - Stack Overflow
Videos
Basically, I wanted the loop to start from the last index and work that way done. However, I am not getting anything.
listr = [10,20,30,50]
count = 0
for i in range(len(listr),-1):
count +=1
print(listr[i], count)
print('-----')Use the built-in reversed() function:
>>> a = ["foo", "bar", "baz"]
>>> for i in reversed(a):
... print(i)
...
baz
bar
foo
To also access the original index, use enumerate() on your list before passing it to reversed():
>>> for i, e in reversed(list(enumerate(a))):
... print(i, e)
...
2 baz
1 bar
0 foo
Since enumerate() returns a generator and generators can't be reversed, you need to convert it to a list first.
You can do:
for item in my_list[::-1]:
print item
(Or whatever you want to do in the for loop.)
The [::-1] slice reverses the list in the for loop (but won't actually modify your list "permanently").
Avoid looping with range, just iterate with a for loop as a general advice.
If you want to reverse a list, use reversed(my_list).
So in your case the solution would be:
my_list = reversed([array0,array1,array2,array3])
That gives you [array3, array2, ...]
For omitting the last array from the reversed list, use slicing:
my_list = reversed([array0,array1,array2,array3])[:-1]
So your code turns to a one liner :-)
You can traverse a list in reverse like so:
for i in range(len(lis), 0, -1):
print (i)
To stop at the second element edit your range() function to stop at 1:
for i in range(len(lis), 1, -1):
print (i)
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
rangeandxrangefunctions in Python 3, there is justrange, which follows the design of Python 2'sxrange.
for x in reversed(whatever):
do_something()
This works on basically everything that has a defined order, including xrange objects and lists.