Sorting list of lists by the first element of each sub-list [duplicate]

Use sorted function along with passing anonymous function as value to the key argument. key=lambda x: x[0] will do sorting according to the first element in each sublist.

>>> lis = [[1,4,7],[3,6,9],[2,59,8]]
>>> sorted(lis, key=lambda x: x[0])
[[1, 4, 7], [2, 59, 8], [3, 6, 9]]

Leave a Comment