Keys in sort method of list

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?

This means that sort (in-place) by value at index 1:

>>> list_of_tuples = [(1, 5), (1, 3), (1, 4)]
>>> list_of_tuples.sort(key=lambda x: x[1])
>>> list_of_tuples
[(1, 3), (1, 4), (1, 5)]
1 Like

Thank you very much.
Quite new here, what does the lambda represent? :slightly_smiling_face:

Does this help? 6. Expressions — Python 3.11.5 documentation

1 Like

lambda creates an anonymous function; a function without a name. It’s basically identical to:

def sort_by_second(x):
    return x[1]


Lambdas are often used for small functions which are only needed in one place.

1 Like

It does, thank you

Well, I see, but I’m still confused about the role of the x here. Is it a parameter / the actual list?

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.

1 Like

Ah, I see and then it will sort according to the elements returned

Following resources from Python documentation may be helpful:

1 Like

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 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).

1 Like

Wow, thanks for the in-depth explanation!!