Hi,
I’m struggling to understand what should go in the key part of the sort method.
For example, I know you can sort a list using the length of member of the list using ‘key=len’ but I don’t know what other examples there are and what are the limitations that within you can operate using the key.
For example, I encountered this code:
list_of_tuples.sort(key=lambda x: x[1])
what does this mean for instance? and in general, are there any common / frequent examples such as this for the key?
Thx
It’s a function parameter, serving the same role as the x in def sort_by_second(x): ...
In this case, sort calls the function supplied in key= once for each of the elements in the list. So x will be each of the elements in the list, one at a time.
Exactly. To illustrate how it works, imagine that we use the function supplied in key= to create a new list, like so:
def sort_by_second(x):
return x[1]
L = [(1, 5), (1, 3), (1, 4)]
L2 = []
for e in L:
L2.append(sort_by_second(e))
L2 will be [5, 3, 4]. Now imagine that we sort L2, and apply the same transformation to the original list. L2 will become [3, 4, 5], i.e. the first element moved to the third position, the second element moved to the first position, and the third element moved to the second position. If L is transformed in the same way, it becomes [(1, 3), (1, 4), (1, 5)].
Which is exactly the same result you get from L.sort(key=sort_by_second).