generic xmerge ?

Alex Martelli aleaxit at yahoo.com
Mon Oct 17 08:07:04 EDT 2005


bonono at gmail.com <bonono at gmail.com> wrote:

> million thanks. So the default compare funcion of heapq also do it like
> sort ?

By defaults, all comparisons in Python occur by the same mechanisms: by
preference, specific comparison operators such as < , <= , and so on
(corresponding to special methods __lt__, __le__, and so on) -- missing
that, the three-way comparison done by built-in function cmp
(corresponding to speial method __cmp__).  For built-in sequences, in
particular (both tuples and lists), the comparisons are lexicographical.

Some (but not all) occasions that imply comparisons let you specify
something else than the default, for example by such mechanisms as the
cmp= optional argument to .sort (which tends to have unpleasant
performance impacts) and the key= optional argument (which tends to have
good performance impact).  heapq does not offer this feature in today's
Python (i.e., 2.4), but I believe it's planned to have it in the future
2.5 release.

But in your case the default comparisons appear to be OK, so you should
have no problem either way.


> The size of the list is not very large but has the potential of being
> run many times(web apps). So I believe second one should be faster(from
> the app perspective) as it goes into the optimized code quickly without
> all the overheads in the merge case.

Yes, the simpler solution may well perform better.  Note that:

L = list(l1)
L.extend(l2)
L.extend(l3)
L.sort()

may perform better than L = sorted(l1+l2+l3) -- if speed matters a lot,
be sure to try (and measure!) both versions.


Alex



More information about the Python-list mailing list