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)
Answer from Chinmay Kanchi on Stack OverflowNote for Python 3 users: There are no separate
rangeandxrangefunctions in Python 3, there is justrange, which follows the design of Python 2'sxrange.
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.
Videos
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?
I would like my iterator to go backward, like, starting from 100 and going to one. Is there a smart way to do this instead of setting a counter into the loop and making it go down by one every time the loop restarts ?
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('-----')