extracting a heapq in a for loop - there must be more elegant solution

Cameron Simpson cs at zip.com.au
Tue Dec 3 22:13:03 CET 2013

On 03Dec2013 12:18, Helmut Jarausch <jarausch at igpm.rwth-aachen.de> wrote:
> I'd like to extracted elements from a heapq in a for loop.
> I feel my solution below is much too complicated.
> How to do it more elegantly? 

I can't believe nobody has mentioned PriorityQueue.

A PriorityQueue (from the queue module in python 3 and the Queue
module in python 2) is essentially just a regular Queue using a
heapq for the storage.

Example (untested):

  from Queue import PriorityQueue

  PQ = PriorityQueue()
  for item in [1,2,3,7,6,5,9,4]:

  while not PQ.empty():
    item = PQ.get()
    ... do stuff with item ...

I iterate over Queues so often that I have a personal class called
a QueueIterator which is a wrapper for a Queue or PriorityQueue
which is iterable, and an IterablePriorityQueue factory function.

  from cs.queues import IterablePriorityQueue

  IPQ = IterablePriorityQueue()
  for item in [1,2,3,7,6,5,9,4]:

  for item in IPQ:
    ... do stuff with item ...

Cameron Simpson <cs at zip.com.au> http://www.cskk.ezoshosting.com/cs/

Those who do not understand Unix are condemned to reinvent it, poorly.
        - Henry Spencer @ U of Toronto Zoology, henry at zoo.toronto.edu

More information about the Python-list mailing list