So I can start from len(collection)
and end in collection[0]
.
EDIT: Sorry, I forgot to mention I also want to be able to access the loop index.
252
50
| |
add a comment
|
412
|
Use the
To also access the original index:
| |||
61
|
You can do:
(Or whatever you want to do in the for loop.) The | ||||||||||||||||
|
32
|
If you need the loop index, and don't want to traverse the entire list twice, or use extra memory, I'd write a generator.
| ||||||||||||||||||||
|
15
|
It can be done like this: for i in range(len(collection)-1, -1, -1): print collection[i] So your guess was pretty close :) A little awkward but it's basically saying: start with 1 less than Fyi, the | ||||||||||||
|
10
|
The
The documentation for reversed explains its limitations. For the cases where I have to walk a sequence in reverse along with the index (e.g. for in-place modifications changing the sequence length), I have this function defined an my codeutil module:
This one avoids creating a copy of the sequence. Obviously, the | ||
2
|
How about without recreating a new list, you can do by indexing:
OR
| ||
1
|
Use | |||
1
|
The other answers are good, but if you want to do as List comprehension style
| ||
1
|
| |||
1
|
OR
|
reversed()
doesn't modify the list.reversed()
doesn't make a copy of the list (otherwise it would require O(N) additional memory). If you need to modify the list usealist.reverse()
; if you need a copy of the list in reversed order usealist[::-1]
. – J.F. Sebastian Feb 9 '09 at 19:27