I want the iterator to move the opposite way, which it moves from the biggest value to the smallest value. How can I do achieve this? I have to give up this convenient way?
Asked
Active
Viewed 280 times
-3
-
iterating over a list from end to start? – Wasi Ahmad Feb 14 '17 at 02:33
-
What are you talking about? Please give some example code! – Klaus D. Feb 14 '17 at 02:34
-
I guess the same question here http://stackoverflow.com/questions/529424/traverse-a-list-in-reverse-order-in-python – Roman Fursenko Feb 14 '17 at 02:35
2 Answers
0
If you're talking about a for loop, you can do
for i in range(start, end, counter)
so if you wanted to iterate from 10 to 0, you would do
for i in range(10, -1, -1)
Remember that the end
in the for loop is exclusive.

JGut
- 532
- 3
- 13
0
Most iterables can be traversed in reverse by using the slice mechanism [::-1]
.
s = "asdf"
for c in s[::-1]:
print c
l = range(5):
for i in l[::-1]:
print i

Logan Byers
- 1,454
- 12
- 19