Python - Sort list of list by specified index
Last Updated :
18 Dec, 2024
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.
Python
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 lists a
based on the 3rd element (x[2]
) of each sublist, as specified in the key
argument using a lambda
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.
Using itemgetter()
Using itemgetter() from the operator module is an efficient way to retrieve elements at specific indices in a list or other iterable.
Python
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.
Python
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 list data
in place, arranging its sublists by the 3rd element (x[2]
) as defined in the key
argument using a lambda
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.
Python
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.
Similar Reads
Python - Returning index of a sorted list We are given a list we need to return the index of a element in a sorted list. For example, we are having a list li = [1, 2, 4, 5, 6] we need to find the index of element 4 so that it should return the index which is 2 in this case.Using bisect_left from bisect modulebisect_left() function from bise
3 min read
Python | sort list of tuple based on sum Given, a list of tuple, the task is to sort the list of tuples based on the sum of elements in the tuple. Examples: Input: [(4, 5), (2, 3), (6, 7), (2, 8)] Output: [(2, 3), (4, 5), (2, 8), (6, 7)] Input: [(3, 4), (7, 8), (6, 5)] Output: [(3, 4), (6, 5), (7, 8)] # Method 1: Using bubble sort Using th
4 min read
Python | Sort a tuple by its float element In this article, we will see how we can sort a tuple (consisting of float elements) using its float elements. Here we will see how to do this by using the built-in method sorted() and how can this be done using in place method of sorting. Examples: Input : tuple = [('lucky', '18.265'), ('nikhil', '1
3 min read
Sort a list of objects by multiple attributes in Python In this article, we are going to learn how to sort a list by multiple attributes with Python. Introduction Python is a dynamically typed language that offers numerous data types, such as list, tuple, set, dictionary, etc. and sorting is the most commonly used operation on any data structures such as
7 min read
Sort a List According to the Length of the Elements - Python We are given a list of strings and our task is to sort the list based on the length of each string. For example, if the input is ["Python", "C", "Java", "JavaScript", "Go"], the output should be ["C", "Go", "Java", "Python", "JavaScript"] since shorter strings come first.Using sorted() sorted() func
3 min read
Sort a list of strings in lexicographical order in Python We are given a list of strings and our task is to sort them in lexicographical order, which means alphabetical order either from A to Z (ascending) or Z to A (descending). This is a common operation when organizing or comparing strings in Python. For example:Input: ["banana", "apple", "cherry", "dat
2 min read