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.

4
  • Check this link, it shows how to write custom comparator. Commented May 24, 2019 at 14:11
  • Maybe take a look at wiki.python.org/moin/HowTo/Sorting. The implementation of sorting CPython uses is 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. Commented May 24, 2019 at 14:11
  • See also: How is sorted(key=lambda x:) implemented behind the scene? Commented May 24, 2019 at 14:18
  • @jonsharpe okay yeah I overlooked the part on converting it to a single value, that makes things much easier Commented May 24, 2019 at 14:20

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.