60

How to sort a list of lists according to the first element of each list?

For example, giving this unsorted list:

[[1,4,7],[3,6,9],[2,59,8]]

The sorted result should be:

[[1,4,7],[2,59,8],[3,6,9]]
glibdud
  • 7,550
  • 4
  • 27
  • 37
Shubham Sharda
  • 653
  • 1
  • 6
  • 5

3 Answers3

75

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]]
Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
32

If you're sorting by first element of nested list, you can simply use list.sort() method.

>>> lis = [[1,4,7],[3,6,9],[2,59,8]]
>>> lis.sort()
>>> lis
[[1, 4, 7], [2, 59, 8], [3, 6, 9]]

If you want to do a reverse sort, you can use lis.reverse() after lis.sort()

>>> lis.reverse()
>>> lis
[[3, 6, 9], [2, 59, 8], [1, 4, 7]]
Miraj50
  • 4,257
  • 1
  • 21
  • 34
Mr. M
  • 321
  • 3
  • 3
13
li = [[1,4,7],[3,6,9],[2,59,8]]
li.sort(key=lambda x: int(x[0]))

This will sort in place changing the original list though. If you want to keep the original list, it is better to use:

sorted(li, key = lambda x: int(x[0]))
greybeard
  • 2,249
  • 8
  • 30
  • 66
Iredra
  • 143
  • 1
  • 10