0

If I have a list of tuples that such as names = [('first1,last1'), ('first2,last2'),...]

I know I can sort them alphabetically with the built-in sort by simply doing

sorted_names = sorted(names, key=lambda tup: (tup[1],tup[0]))

However, I want to know how exactly python is using the key. For instance, if I wanted to make my own sort function with a key parameter how would it be implemented? My guess would be something like

def my_sort(list, key):
    interpret the key in some way
    sort the list based on the key
    return list

I've looked through the documentation and couldn't find what I was looking for.

vlovero
  • 190
  • 1
  • 11
  • Check this [link](https://stackoverflow.com/questions/5213033/sort-list-of-list-with-custom-compare-function-in-python), it shows how to write custom comparator. – vb_rises May 24 '19 at 14:11
  • Maybe take a look at https://wiki.python.org/moin/HowTo/Sorting. The implementation of sorting CPython uses is [Timsort](https://en.wikipedia.org/wiki/Timsort). The key is used to convert each item in the thing you're sorting into a single value that reflects how you want it to be sorted (in this case, that value is *also* a tuple). If you're asking how Python sorts tuples: element-wise. – jonrsharpe May 24 '19 at 14:11
  • See also: [How is sorted(key=lambda x:) implemented behind the scene?](https://stackoverflow.com/questions/41078689/how-is-sortedkey-lambda-x-implemented-behind-the-scene) – Patrick Haugh May 24 '19 at 14:18
  • @jonsharpe okay yeah I overlooked the part on converting it to a single value, that makes things much easier – vlovero May 24 '19 at 14:20

0 Answers0