[NEWBIE] Priority Queue in Python

Fredrik Lundh fredrik at effbot.org
Sat Feb 3 15:35:01 EST 2001


David Boeren wrote:
> Also, one specific question.  Maybe it's because I don't know the
> idioms yet, but I keep wanting to have access to a loop counter
> variable in my for loops.  For example:
>
> for i in list:
>     print i, "is the", list.index(i), "element"

Ouch.

> The index() call takes too long, I wish there was like a hidden
> variable so I could say it like this.  Is there?
>
> for i in list:
>     print i, "is the", __loopindex__, "element"
>
> Or is there just a better way to do this that I don't know?

There's is an index counter deep inside Python, but you
cannot access it from the "outside" [1].  But there are
more efficient ways to do what you want:

    for i in range(len(list)):
        item = list[i]
        print item, "is the", i, "element"

or

    i = 0
    for item in list:
        print item, "is the", i, "element"
        i += 1

Cheers /F

1) the counter is passed to the list's __getitem__ method.
you can wrap the list in an adapter object whose __getitem__
method returns both the element and the index as a tuple
(but don't do that if you care about performance).





More information about the Python-list mailing list