Python - Sort Tuple List by Nth Element of Tuple
Last Updated :
11 Feb, 2025
We are given list of tuple we need to sort tuple by Nth element of each tuple. For example d = [(1, 5), (3, 2), (2, 8), (4, 1)] and k=1 we need to sort by 1st element of each tuple so that output for given list should be [(4, 1), (3, 2), (1, 5), (2, 8)]
Using sorted()
with lambda
sorted() function with a lambda key sorts a list of tuples based on Nth element by specifying lambda x: x[n]. It provides an efficient and concise way to perform element-wise tuple sorting
Python
d = [(1, 5), (3, 2), (2, 8), (4, 1)]
n = 1
# Sort the list based on the Nth element using a lambda function
res = sorted(d, key=lambda x: x[n])
print(res)
Output[(4, 1), (3, 2), (1, 5), (2, 8)]
Explanation:
- sorted() function sorts the list of tuples based on the nth element (index 1 in this case) using lambda x: x[n], meaning it sorts by second value in each tuple.
- Output will be [(4, 1), (3, 2), (1, 5), (2, 8)] as second elements [5, 2, 8, 1] are sorted in ascending order [1, 2, 5, 8].
Using operator.itemgetter()
operator.itemgetter(n) function retrieves the Nth element from each tuple allowing sorted() to sort list based on that element. It is more efficient than using a lambda function for tuple-based sorting.
Python
from operator import itemgetter
d = [(1, 5), (3, 2), (2, 8), (4, 1)]
n = 1
# Sort using itemgetter, which is optimized for retrieving elements by index
res = sorted(d, key=itemgetter(n))
print(res)
Output[(4, 1), (3, 2), (1, 5), (2, 8)]
Explanation:
- itemgetter(n) function retrieves nth element from each tuple, allowing sorted() to arrange list based on that value.
- This method is more efficient than using a lambda function because itemgetter is implemented in C making it faster for large datasets.
Using pandas.DataFrame
A pandas.DataFrame
allows storing list of tuples as a structured table and sorting it efficiently using .sort_values
()
method. This approach is useful for handling large datasets as Pandas provides optimized sorting and additional data manipulation features.
Python
import pandas as pd
d = [(1, 5), (3, 2), (2, 8), (4, 1)]
# Convert the list of tuples into a Pandas DataFrame
df = pd.DataFrame(d)
# Sort DataFrame by the second column (index 1) and convert back to list of tuples
res = df.sort_values(by=1).values.tolist()
print(res)
Output[[4, 1], [3, 2], [1, 5], [2, 8]]
Explanation:
- List of tuples is converted into a Pandas DataFrame, where each tuple represents a row, making it easy to manipulate the data.
- sort_values(by=1) method sorts the DataFrame based on the second column (index 1), and .values.tolist() converts the sorted DataFrame back into a list of tuples.
Similar Reads
Swap tuple elements in list of tuples - Python The task of swapping tuple elements in a list of tuples in Python involves exchanging the positions of elements within each tuple while maintaining the list structure. Given a list of tuples, the goal is to swap the first and second elements in every tuple. For example, with a = [(3, 4), (6, 5), (7,
3 min read
Sort Tuple of Lists in Python The task of sorting a tuple of lists involves iterating through each list inside the tuple and sorting its elements. Since tuples are immutable, we cannot modify them directly, so we must create a new tuple containing the sorted lists. For example, given a tuple of lists a = ([2, 1, 5], [1, 5, 7], [
3 min read
Python | Sort tuple based on occurrence of first element Given a list of tuples, write a Python program to sort the list based on the occurrence of first element of tuples. Examples: Input : [(1, 'Jake'), (2, 'Bob'), (1, 'Cara')] Output : [(1, 'Jake', 'Cara', 2), (2, 'Bob', 1)] Input : [('b', 'ball'), ('a', 'arm'), ('b', 'b'), ('a', 'ant')] Output : [('a'
3 min read
Python - Sort by Frequency of second element in Tuple List Given list of tuples, sort by frequency of second element of tuple. Input : test_list = [(6, 5), (1, 7), (2, 5), (8, 7), (9, 8), (3, 7)] Output : [(1, 7), (8, 7), (3, 7), (6, 5), (2, 5), (9, 8)] Explanation : 7 occurs 3 times as 2nd element, hence all tuples with 7, are aligned first. Input : test_l
6 min read
Sort a List of Tuples by Second Item - Python The task of sorting a list of tuples by the second item is common when working with structured data in Python. Tuples are used to store ordered collections and sometimes, we need to sort them based on a specific element, such as the second item. For example, given the list [(1, 3), (4, 1), (2, 2)],
2 min read
Python program to Sort Tuples by their Maximum element Given a Tuple List sort tuples by maximum element in a tuple. Input : test_list = [(4, 5, 5, 7), (1, 3, 7, 4), (19, 4, 5, 3), (1, 2)] Output : [(19, 4, 5, 3), (4, 5, 5, 7), (1, 3, 7, 4), (1, 2)] Explanation : 19 > 7 = 7 > 2, is order, hence reverse sorted by maximum element. Input : test_list
5 min read