So I can start from len (collection) and end in collection[0].
EDIT: Also sorry forgot to mention, I also want to be able to access the loop index.
So I can start from len (collection) and end in collection[0].
EDIT: Also sorry forgot to mention, I also want to be able to access the loop index.
Use the reversed()
built-in function:
>>> a = ["foo", "bar", "baz"]
>>> for i in reversed(a):
... print i
...
baz
bar
foo
To also access the original index:
>>> for i, e in reversed(list(enumerate(a))):
... print i, e
...
2 baz
1 bar
0 foo
the reverse function comes in handy here:
myArray = [1,2,3,4]
myArray.reverse()
for x in myArray:
print x
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").
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.
def reverse_enum(L):
for index in reversed(xrange(len(L))):
yield index, L[index]
L = ['foo', 'bar', 'bas']
for index, item in reverse_enum(L):
print index, item
Can it be done like so?:
for i in range (len(collection):0) :
print collection[i]
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 len(collection)
, keep going until you get to just before -1, by steps of -1.
Fyi, the help
function is very useful as it lets you view the docs for something from the Python console, eg:
help(range)