An example:
names = ["George Washington", "John Adams", "Thomas Jefferson", "James Madison"]
sorted(names, key=lambda name: name.split()[-1].lower())
I know key
is used to compare different names, but it can have two different implementations:
- First compute all keys for each name, and bind the key and name together in some way, and sort them. The p
- Compute the key each time when a comparison happens
The problem with the first approach is that it has to define another data structure to bind the key and data. The problem with the second approach is that the key might be computed for multiple times, that is, name.split()[-1].lower()
will be executed many times, which is very time-consuming.
I am just wondering in which way Python implemented sorted()
.
The key function is executed just once per value, to produce a
(keyvalue, value)
pair; this is then used to sort and later on just the values are returned in the sorted order. This is sometimes called a Schwartzian transform.You can test this yourself; you could count how often the function is called, for example:
or you could collect all the values that are being passed in; you'll see that they follow the original input order:
If you want to read the CPython source code, the relevant function is called
listsort()
, and thekeyfunc
is used in the following loop (saved_ob_item
is the input array), which is executed before sorting takes place:so in the end, you have two arrays, one with
keys
and one with the original values. All sort operations act on the two arrays in parallel, sorting the values inlo.keys
and moving the elements inlo.values
in tandem.