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]]
If you're sorting by first element of nested list, you can simply use list. sort() method.
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.
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.
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.
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]]
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]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With