Show the difference between Python's list.sort() method and the sorted() function, including the key argument.
sort is a method on the list and modifies it in place. sorted is a function that takes any iterable and returns a new sorted list, leaving the original alone.
numbers = [3, 1, 2]
result = numbers.sort()
print(result) # None - sort returns nothing
print(numbers) # [1, 2, 3] - but the list is sorted
copy = sorted([3, 1, 2], reverse=True)
print(copy) # [3, 2, 1]
print([3, 1, 2]) # [3, 1, 2] - the original is untouched
# The key argument chooses what to sort on
words = ["banana", "fig", "apple"]
print(sorted(words, key=len)) # ['fig', 'apple', 'banana']The None that sort returns is the detail that catches people out, because it means the whole statement result = numbers.sort() does nothing useful. If you find that in your own code, you want sorted instead.
The key argument is where most of the real work happens. It takes a function that is applied to each element to produce the value used for comparison, and the original elements are what end up in the result — so sorting by len gives the words in order of length but still spelled normally. The reverse=True argument flips the order without needing a reversed key function.
Two more things to know. Python's sort is stable, so elements that compare equal keep their original relative order, which matters when you sort by one field of a record and want the other fields to stay in a predictable order. And a key function is called exactly once per element, so it is the right place to put an expensive computation — writing a lambda that recomputes a value on every comparison is a well-known performance mistake.