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.
python - Loop backwards using indices - Stack Overflow
Why isn't my loop iterating backwards in python?
How can I loop through an array forward and then backwards and then forwards and... etc with the modulus operator?
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('-----')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?
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").
I want to iterate over a string in reverse. I googled it and found this way
for i in range(len(k)-1, 0-1, -1):
but to be honest I don't understand it. can you please explain it to me?
also, I would love it if you guys can suggest other methods