Python List Sort Key

Every computer scientist loves sorting things. In this article, I’ll show you how you can modify the default Python sorting behavior with the key argument.

Definition and Usage: To customize the default sorting behavior of the list.sort() and sorted() method, use the optional key argument by passing a function that returns a comparable value for each element in the list.

Here’s a short overview example that shows you how to use the arguments in practice:

# Create an unsorted integer list
lst = [88, 12, 42, 11, 2]

# Sort the list in place (ascending)
lst.sort()
print(lst)
# [2, 11, 12, 42, 88]

# Sort the list

Continue reading the original article