Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting list of lists by the first element of each sub-list

Tags:

python

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]] 
like image 481
Shubham Sharda Avatar asked Apr 30 '16 13:04

Shubham Sharda


People also ask

How do you sort a list by first element?

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

How do you sort a list with multiple elements?

To sort a list of tuples by multiple elements in Python: Pass the list to the sorted() function. Use the key argument to select the elements at the specific indices in each tuple. The sorted() function will sort the list of tuples by the specified elements.

Can you sort a list of lists in Python?

You can sort a list in Python using the sort() method. The method accepts two optional arguments: reverse : which sorts the list in the reverse order (descending) if True or in the regular order (ascending) if False (which it is by default) key : a function you provide to describe the sorting method.

Can you sort nested list?

There will be three distinct ways to sort the nested lists. The first is to use Bubble Sort, the second is to use the sort() method, and the third is to use the sorted() method.


2 Answers

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]] 
like image 112
Avinash Raj Avatar answered Sep 20 '22 13:09

Avinash Raj


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]] 
like image 24
Mr. M Avatar answered Sep 23 '22 13:09

Mr. M