How does the key argument in python’s sorted function work?

The function you pass in to key is given each of the items that are being sorted, and returns a “key” that Python can sort by. So, if you want to sort a list of strings by the reverse of the string, you could do this:

list_of_strings.sort(key=lambda s: s[::-1])

This lets you specify the value each item is sorted by, without having to change the item. That way, you don’t have to build a list of reversed strings, sort that, then reverse them back.

# DON'T do this

data = ['abc', 'def', 'ghi', 'jkl']
reversed_data = [s[::-1] for s in data]
reversed_data.sort()
data = [s[::-1] for s in reversed_data]

# Do this

data.sort(key=lambda s: s[::-1])

In your case, the code is sorting each item by the second item in the tuple, whereas normally it would initially sort by the first item in the tuple, then break ties with the second item.

Leave a Comment