heapq "key" arguments

Joshua Bronson jabronson at gmail.com
Fri Jul 31 13:44:33 EDT 2009


According to http://docs.python.org/library/heapq.html, Python 2.5
added an optional "key" argument to heapq.nsmallest and
heapq.nlargest. I could never understand why they didn't also add a
"key" argument to the other relevant functions (heapify, heappush,
etc). Say I want to maintain a heap of (x, y) pairs sorted only by
first coordinate. Without being able to pass key=itemgetter(0), won't
heapifying a list of such pairs unnecessarily compare both
coordinates? And worse, if the second coordinate is actually an object
with no ordering defined for it, heapifying will cause an error even
though all I care about is sorting by the first coordinate, which does
have an ordering. Am I missing something?



More information about the Python-list mailing list