How Does sorted(list_arg1, key=arg2) Work in Python?

You see that Python's sorted reserved word has an option to use a key (rather than the default mechanism). How does the key parameter/flag in Python's sorted function work?

Short Answer:
The word "key" designates a special function that you create. It accepts two parameters and returns positive or negative numbers. These help give you the ability to sort the list in a non-standard way.

Detailed Answer:
"The value (or values) that determines the sorting order is referred to as the key." (This quote was taken from page 144 of Programming Interviews Exposed.)

The function is invoked as a key with syntax like this:

sorted(contint_list, key=functools.cmp_to_key(cool_comp))

This function "cool_comp" is the arbitrary name and "cmp_to_key" is part of the "functools" library. (The above would need "import functools" in the Python program to work properly; it would also need "cool_comp" or whatever function name you choose to be defined). This "cool_comp" can return different values. However if it returns a True or False, the regular "sorted" feature will happen with default functionality (as if no key= was designated).

If the function in the key ("cool_comp" in this example) of sorted returns negative numbers (integers or decimals), the function will change the position of the two values in comparison.

In the sorted() keyword, if the function returns a negative value, the two values in the list will be swapped. If the function returns a positive value, the two values in the list will not be swapped.

The function via "key=functools.cmp_to_key(foobar)" syntax will be called with sending to parameters from the list. It will start with the leftmost two elements and iterate toward the right (taking two elements in the list at a time). The number of comparisons varies based on what is in the list and their current order. Some lists are almost already in order while others are in reverse order or random order.

The function "foobar" (or "cool_comp" in the example above) as an optional "key" function for the "sorted" feature should be defined to accept two parameters exactly.

Often sorting involves alphabetizing or ordering numbers in a sequence from small to large. However some sorting for complex use-cases may not be this trivial. Thus keys are involved for handling a composite number of smaller components/inputs for sophisticated sorting beyond ordering numbers or letters in default fashions. Incorporating a second component, such as a sequence of integers to the items in the array, can facilitate tracking whether the sorting algorithm is "stable." A sorting algorithm is said to be "stable" if it preserves the original order in the case of two equivalent keys. Some keys are not unique and their corresponding elements are how a person knows if the original order is preserved after the sorting of the array.

In some cases the key is very complex -- handling multiple data points with a formula that is based on a computation involving these different factors. With these types of keys, swapping the position of two elements in a list is a faster and less resource intensive operation than comparing the two elements. In these cases, selection sort may be an optimal/performant solution (per page 145 of Programming Interviews Exposed). We believe that implementing a sorting algorithm beyond the sorted reserved word and including a key, such as coding selection sort, would be rare in a business environment but possible in an interview.

If you want to purchase a book on Python, see this posting.

Leave a comment

Your email address will not be published. Required fields are marked *