Sorting a Python list by two fields

No need to import anything when using lambda functions.
The following sorts list by the first element, then by the second element. You can also sort by one field ascending and another descending for example:

sorted_list = sorted(list, key=lambda x: (x[0], -x[1]))

Leave a Comment