[Python-ideas] Optimizing list.sort() by checking type in advance

Jonathan Goble jcgoble3 at gmail.com
Mon Oct 10 23:52:48 EDT 2016


On Mon, Oct 10, 2016 at 11:30 PM Elliot Gorokhovsky <
elliot.gorokhovsky at gmail.com> wrote:

> - I expect tuples will also be worth specializing (complex sort keys are
> often implemented as tuples).
>
> I'm not sure what you mean here... I'm looking at the types of lo.keys,
> not of saved_ob_item (I think I said that earlier in this thread by mistake
> actually). So if someone is passing tuples and using itemgetter to extract
> ints or strings or whatever, the current code will work fine; lo.keys will
> be scalar types. Unless I misunderstand you here. I mean, when would
> lo.keys actually be tuples?
>

If someone wanted to sort, e.g., a table (likely a list of tuples) by
multiple columns at once, they might pass the key function as
`itemgetter(3, 4, 5)`, meaning to sort by "column" (actually item) 3, then
columns 4 and then 5 as tiebreakers. This itemgetter will return a new
tuple of three items, that tuple being the key to sort by. Since tuples
sort by the first different item, in this theoretical example the result of
sort() will be exactly what the user wanted: a table sorted by three
columns at once.

A practical example of such a use case is sorting by last name first and
then by first name where two people have the same last name. Assuming a
list of dicts in this case, the key function passed to sort() would simply
be `itemgetter('lastname", "firstname")`, which returns a tuple of two
items to use as the key.

So yes, there are perfectly valid use cases for tuples as keys.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20161011/485883d0/attachment-0001.html>


More information about the Python-ideas mailing list