Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are python sort keys guaranteed to be called only once?

Tags:

python

sorting

While answering another question, I ended up creating a sortkey function which modified a dictionary in order to save state which would then be used for subsequent items in the sort.

While my answer seemed to work, my question is this: Is it actually defined in the python documentation that the sort-key would only be called once per object? Is this is an implementation detail of Cpython? Or is the sort-key actually called more than once and I got the correct answer only out of luck?

The documentation of sorted states:

key specifies a function of one argument that is used to extract a comparison key from each list element: key=str.lower. The default value is None (compare the elements directly)

Which I don't think implies that key will only be called once per element ... but it could be stated elsewhere.

Obviously I ask as this has consequences on any sort-keys which have a side effect.

like image 344
mgilson Avatar asked Nov 15 '12 04:11

mgilson


People also ask

How does key work in Python sort?

Custom Sorting With key= For example with a list of strings, specifying key=len (the built in len() function) sorts the strings by length, from shortest to longest. The sort calls len() for each string to get the list of proxy length values, and then sorts with those proxy values.

Does Python sort preserve order?

Sorts are guaranteed to be stable. That means that when multiple records have the same key, their original order is preserved.

Does sorted always return a list?

sorted simply always returns a new list object from an arbitrary iterable. The type of the iterable is irrelevant.

Is sort () or sorted () faster?

sort is 13% faster than sorted .


1 Answers

From the section of the docs you link:

In general, the key and reverse conversion processes are much faster than specifying an equivalent cmp function. This is because cmp is called multiple times for each list element while key and reverse touch each element only once.

That would seem to be a "yes" ...

like image 125
Zero Piraeus Avatar answered Oct 15 '22 22:10

Zero Piraeus