paul_k
paul_k

Reputation: 47

Iteration through lists of different length

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

Answers (3)

mac
mac

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:

  • Acorn's method [using .reverse()] modifies the list in place
  • Using reversed() would create an iterator object
  • My method doesn't do any of the previous two

Using .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

gomad
gomad

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

Acorn
Acorn

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

Related Questions