Nasty gotcha/bug in heapq.nlargest/nsmallest

Raymond Hettinger python at rcn.com
Fri May 30 23:46:07 EDT 2008


On May 15, 12:06 am, Peter Otten <__pete... at web.de> wrote:
> According
> to my ad hoc test you need <, <=, and == for nlargest()/nsmallest() to
> work:

In Py2.6 and after, you only need < and ==.  I replaced the LE tests
with LT to match list.sort() and bisect.bisect().  The == arises
because nlargest/nsmallest compare decorated tuples.  Tuple comparison
always starts with equality tests to find the first unequal element
and then switches back to testing whichever inequality test was
requested.

Raymond



More information about the Python-list mailing list