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

rusi rustompmody at gmail.com
Tue Dec 3 07:40:26 EST 2013


On Tuesday, December 3, 2013 5:48:59 PM UTC+5:30, Helmut Jarausch wrote:
> Hi,
>
> 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 know I could use a while loop but I don't like it.

How about

def in_sequence(h):
  for i in range(len(h)):
    yield heapq.heappop(h)

Yeah its a bit fiddly:
1. i needed for for but not used
2. The range in the for loop -- normally a python 'smell'

If python3

def ins3(h):
   yield from (heapq.heappop(h) for i in range(len(h)))




More information about the Python-list mailing list