![]() |
In Python, sorting a list of lists by the first element of each sub-list is a common task. Whether you’re dealing with data points, coordinates, or any other structured information, arranging the lists based on the values of their first elements can be crucial. In this article, we will sort a list of lists by the first element of each sub-list. This process organizes the outer list based on the values of the first elements in its sub-lists. Here, we’ll explore different methods to achieve this task. Python Sorting List Of Lists By The First Element Of Each Sub-ListBelow are some of the ways by which we can sort the list of lists by the first element of each sub-list in Python:
Sorting List Of Lists by First Element Using
|
# Using the sorted() Function with a Lambda Function list_of_lists = [[ 3 , 'b' ], [ 1 , 'a' ], [ 2 , 'c' ]] sorted_list = sorted (list_of_lists, key = lambda x: x[ 0 ]) #Display the sorted print (sorted_list) |
[[1, 'a'], [2, 'c'], [3, 'b']]
In this approach, we are using the sort()
method with a Custom Comparator as the key to sort the list in-place based on the first element of each sub-list.
#Using the sort() Method with a Custom Comparator list_of_lists = [[ 3 , 'b' ], [ 1 , 'a' ], [ 2 , 'c' ]] list_of_lists.sort(key = lambda x: x[ 0 ]) #Display the sorted list print (list_of_lists) |
[[1, 'a'], [2, 'c'], [3, 'b']]
One of the way is to use List comprehension along with the sorted()
function to create a new sorted list based on the first element of each sub-list.
# Using List Comprehension with Sorted list_of_lists = [[ 3 , 'b' ], [ 1 , 'a' ], [ 2 , 'c' ]] sorted_list = [x for x in sorted (list_of_lists, key = lambda x: x[ 0 ])] #Display sorted list print (sorted_list) |
[[1, 'a'], [2, 'c'], [3, 'b']]
itemgetter()
FunctionOne of the ways is to use itemgetter function from the operator module as the key argument in the sorted() function to achieve sorting based on the first element of each sub-list.
# Using the itemgetter Function from the operator Module from operator import itemgetter list_of_lists = [[ 3 , 'b' ], [ 1 , 'a' ], [ 2 , 'c' ]] sorted_list = sorted (list_of_lists, key = itemgetter( 0 )) # Display sorted list print (sorted_list) |
[[1, 'a'], [2, 'c'], [3, 'b']]
In this method custom sorting function is defined, and this function is used as the key argument in the sorted()
function to sort the list based on the first element of each sub-list.
# Using a Custom Function def custom_sort(sub_list): return sub_list[ 0 ] list_of_lists = [[ 3 , 'b' ], [ 1 , 'a' ], [ 2 , 'c' ]] sorted_list = sorted (list_of_lists, key = custom_sort) #Display list in sorted order print (sorted_list) |
[[1, 'a'], [2, 'c'], [3, 'b']]
Reffered: https://www.geeksforgeeks.org
Python |
Related |
---|
![]() |
![]() |
![]() |
![]() |
![]() |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 16 |