Reputation: 47
I have to use a backwards loop:
for i in range(len(my_ls))[::-1]:
print i
But some of the lists have length = 1
(as in ['one']
).
As a result the interpreter prints nothing at all.
Nevertheless, in python's own shell it works all right and 0 is printed, as was planned.
Any ideas how to overcome this problem?
I run Python 2.6.6 on Debian Squeeze.
Upvotes: 0
Views: 743
Reputation: 43031
Is this what you are trying to achieve?
>>> li = ['one']
>>> for i in range(len(li)-1, -1, -1):
... print li[i]
...
one
EDIT: The difference between my answer and Acorn's one is that:
.reverse()
] modifies the list in placereversed()
would create an iterator objectUsing .reverse()
or reversed()
is more idiomatic in python. But the range
parameters are there to give you this possibility too (memory-wise I'm not sure if my method has any advantage over reversed()
though!).
HTH!
Upvotes: 1
Reputation: 1039
First of all, all you're going to print out there is the offset of each item from the end of the range, not the items in the list at all.
The range looks like you're trying to write C in Python, to me.
What you want is something like this:
>>> l = ['one']
>>> for each in l[-1::-1]:
>>> print each
...
one
>>> l.append('two')
>>> for each in l[-1::-1]:
>>> print each
...
two
one
The construction for each in l[-1::-1]
iterates from the end of the list to the start of the list, regardless of list size and without the awkward involvement of range
.
Upvotes: 0
Reputation: 50497
Could you not just pass the list to reversed()
[docs] and then iterate over the resulting reverse iterator?
for x in reversed(lst):
print x
Upvotes: 4