How do I sort this list in Python 3? [duplicate]

You are correct, you can use the sorted() function or .sort() method.

I can see two options to sort in the way you want; both required basing the sort on the first element of the sub-lists; which must be converted to integers.

You can then either base it directly on this heuristic, but then you will have to use reverse=True as an argument to the function so that you get highest to lowest sorting. Or, you can just use a little hack and sort based on the negative of each of these integers :).

l = [['56', 'UsernameA'], ['73', 'UsernameB'], ['52', 'UsernameC'], ['10', 'UsernameD']]
l.sort(key=lambda j: -int(j[0]))

which modifies l to:

[['73', 'UsernameB'], ['56', 'UsernameA'], ['52', 'UsernameC'], ['10', 'UsernameD']]

Browse More Popular Posts

Leave a Comment