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

Jussi Piitulainen jpiitula at ling.helsinki.fi
Tue Dec 3 14:56:11 CET 2013

Helmut Jarausch writes:
> I know I could use a while loop but I don't like it.
> from heapq import heappush, heappop
> # heappop raises IndexError if heap is empty
> # how to avoid / simplify the following function
> def in_sequence(H) :
>   try :
>     while True :
>       N= heappop(H)
>       yield N
>   except IndexError :
>     raise StopIteration

That seems equivalent to this:

def in_sequence(H):
  while H: yield heappop(H)

But I don't like the side-effect. I'd change the name to something
that indicates the draining of the heap - heapaerobic? - or consider
sorted(H) instead as others suggested.

More information about the Python-list mailing list