Python – Sort list of list by specified index
When working with a list of lists, we often need to sort the inner lists based on the values at a specific index. Sorting by a specified index is useful in the custom ordering of multidimensional data. In this article, we will explore different ways to sort a list of lists by a specified index in Python.
Using sorted()
The most simple and efficient way to sort a list of lists by a specified index is using the sorted()
function with a key
. It is efficient and concise for sorting by any index.
a = [[1, 'Python', 50], [2, 'with', 30], [3, 'GFG', 40]]
# Sorting by the 2nd index
b = sorted(a, key=lambda x: x[2])
print(b)
Output
[[2, 'with', 30], [3, 'GFG', 40], [1, 'Python', 50]]
Explanation:
- The
sorted()
function sorts the list of listsa
based on the 3rd element (x[2]
) of each sublist, as specified in thekey
argument using alambda
function. - The output is a new list where sublists are ordered by their price values (the 3rd element). The original list remains unchanged.
Let’s explore some other methods to check how we can sort list of list by specified index.
Table of Content
Using itemgetter()
Using itemgetter() from the operator module is an efficient way to retrieve elements at specific indices in a list or other iterable.
from operator import itemgetter
a = [[1, 'Python', 50], [2, 'is', 30], [3, 'fun!', 40]]
# Sorting by the 2nd index
b = sorted(a, key=itemgetter(2))
print(b)
Output
[[2, 'is', 30], [3, 'fun!', 40], [1, 'Python', 50]]
Explanation:
itemgetter(2)
fetches the value at the specified index.- This method is often more efficient than using a lambda function, especially with large datasets, as it avoids using lambda.
Using list.sort()
list.sort()
method is used to sort a list in place, meaning it rearranges the elements of the list without creating a new list.
a = [[1, 'Python', 50], [2, 'is', 30], [3, 'fun!', 40]]
# Sorting in place by the 2nd index
a.sort(key=lambda x: x[2])
print(a)
Output
[[2, 'is', 30], [3, 'fun!', 40], [1, 'Python', 50]]
Explanation:
sort()
method modifies the listdata
in place, arranging its sublists by the 3rd element (x[2]
) as defined in thekey
argument using alambda
function.- Unlike
sorted()
, this does not create a new list but directly updates the original list, saving memory.
Sorting by Multiple Indices
Sometimes, we may want to sort a list by multiple indices in hierarchical order. It is useful for sorting data with ties at the first index.
a = [[1, 'Python', 50], [2, 'is', 30], [3, 'fun!', 40]]
# Sorting by 2nd index first, then by 0th index
sorted_data = sorted(a, key=lambda x: (x[1], x[0]))
print(sorted_data)
Output
[[1, 'Python', 50], [3, 'fun!', 40], [2, 'is', 30]]
Explanation:
- The
key=lambda x: (x[1], x[0])
is a tuple that allows for multi-level sorting. Python compares tuples element by element, so it first sorts by the second element and resolves ties by the first element.