Open In App

Python | Sort Tuples in Increasing Order by any key

Last Updated : 14 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given a tuple, sort the list of tuples in increasing order by any key in tuple. Examples:

Input : tuple = [(2, 5), (1, 2), (4, 4), (2, 3)] 
            m = 0
Output : [(1, 2), (2, 3), (2, 5), (4, 4)]
Explanation: Sorted using the 0th index key.

Input :  [(23, 45, 20), (25, 44, 39), (89, 40, 23)]
         m = 2
Output : Sorted: [(23, 45, 20), (89, 40, 23), (25, 44, 39)] 
Explanation: Sorted using the 2nd index key

Given tuples, we need to sort them according to any given key. This can be done using sorted() function where we sort them using key=last and store last as the key index according to which we have to sort the given tuples. Below is the Python implementation of the above approach: 

Python




# Python code to sort a list of tuples
# according to given key.
 
# get the last key.
def last(n):
    return n[m] 
  
# function to sort the tuple  
def sort(tuples):
 
    # We pass used defined function last
    # as a parameter.
    return sorted(tuples, key = last)
  
# driver code 
a = [(23, 45, 20), (25, 44, 39), (89, 40, 23)]
m = 2
print("Sorted:"),
print(sort(a))


Output:

Sorted: [(23, 45, 20), (89, 40, 23), (25, 44, 39)] 

Another  approach  is  using the operator.itemgetter() function from the operator module. The itemgetter() function returns a callable object that can be used to retrieve an item from an object, such as a tuple.

Here is an example of how to use itemgetter() to sort a list of tuples by any key:

Python3




import operator
 
def sort_tuples(tuples, key):
    return sorted(tuples, key=operator.itemgetter(key))
 
tuples = [(2, 5), (1, 2), (4, 4), (2, 3)]
key = 0
print(sort_tuples(tuples, key))  # Output: [(1, 2), (2, 3), (2, 5), (4, 4)]


Output

[(1, 2), (2, 5), (2, 3), (4, 4)]

This approach has the advantage of being concise and efficient, as it uses the built-in sorted() function and the itemgetter() function from the operator module. It is also easy to understand and implement.

Note that the itemgetter() function returns a callable object that can be used to retrieve an item from an object, such as a tuple. To sort the tuples, we pass this callable object to the key argument of the `sorted

Approach#3: Using lambda

One way to sort tuples in increasing order by any key is to use the sorted function and pass a key function that returns the desired element of each tuple.

Algorithm

1. Define a key function that returns the desired element of each tuple.
2. Use the sorted function to sort the list of tuples using the key function.

Python3




def sort_tuples(tuples, key_idx):
    # Step 1: Define a key function that returns the desired element of each tuple.
    key_func = lambda x: x[key_idx]
 
    # Step 2: Use the `sorted` function to sort the list of tuples using the key function.
    sorted_tuples = sorted(tuples, key=key_func)
 
    return sorted_tuples
 
# Example usage:
tuples = [(2, 5), (1, 2), (4, 4), (2, 3)]
sorted_tuples = sort_tuples(tuples, 0)
print(sorted_tuples)
 
tuples = [(23, 45, 20), (25, 44, 39), (89, 40, 23)]
sorted_tuples = sort_tuples(tuples, 2)
print(sorted_tuples)


Output

[(1, 2), (2, 5), (2, 3), (4, 4)]
[(23, 45, 20), (89, 40, 23), (25, 44, 39)]

Time Complexity: O(n log n), where n is the number of tuples in the list. This is because sorting takes O(n log n) time in the worst case.
Space Complexity: O(n), where n is the number of tuples in the list. This is because we create a new sorted list of tuples.



Similar Reads

Python program to Sort a List of Tuples in Increasing Order by the Last Element in Each Tuple
The task is to write a Python Program to sort a list of tuples in increasing order by the last element in each tuple. Input: [(1, 3), (3, 2), (2, 1)] Output: [(2, 1), (3, 2), (1, 3)] Explanation: sort tuple based on the last digit of each tuple. Methods #1: Using sorted(). Sorted() method sorts a list and always returns a list with the elements in
7 min read
Sort all even numbers in ascending order and then sort all odd numbers in descending order
Given an array of integers (both odd and even), sort them in such a way that the first part of the array contains odd numbers sorted in descending order, rest portion contains even numbers sorted in ascending order.Examples: Input: arr[] = {1, 2, 3, 5, 4, 7, 10}Output: arr[] = {7, 5, 3, 1, 2, 4, 10} Input: arr[] = {0, 4, 5, 3, 7, 2, 1}Output: arr[]
15+ min read
Python | Remove duplicate tuples from list of tuples
Given a list of tuples, Write a Python program to remove all the duplicated tuples from the given list. Examples: Input : [(1, 2), (5, 7), (3, 6), (1, 2)] Output : [(1, 2), (5, 7), (3, 6)] Input : [('a', 'z'), ('a', 'x'), ('z', 'x'), ('a', 'x'), ('z', 'x')] Output : [('a', 'z'), ('a', 'x'), ('z', 'x')] Method #1 : List comprehension This is a naive
5 min read
Python | Find the tuples containing the given element from a list of tuples
Given a list of tuples, the task is to find all those tuples containing the given element, say n. Examples: Input: n = 11, list = [(11, 22), (33, 55), (55, 77), (11, 44)] Output: [(11, 22), (11, 44)] Input: n = 3, list = [(14, 3),(23, 41),(33, 62),(1, 3),(3, 3)] Output: [(14, 3), (1, 3), (3, 3)] There are multiple ways we can find the tuples contai
6 min read
Python | Remove tuples from list of tuples if greater than n
Given a list of a tuple, the task is to remove all the tuples from list, if it's greater than n (say 100). Let's discuss a few methods for the same. Method #1: Using lambda STEPS: Initialize a list of tuples: ini_tuple = [('b', 100), ('c', 200), ('c', 45), ('d', 876), ('e', 75)]Print the initial list: print("intial_list", str(ini_tuple))Define the
6 min read
Python | Remove tuples having duplicate first value from given list of tuples
Given a list of tuples, the task is to remove all tuples having duplicate first values from the given list of tuples. Examples: Input: [(12.121, 'Tuple1'), (12.121, 'Tuple2'), (12.121, 'Tuple3'), (923232.2323, 'Tuple4')] Output: [(12.121, 'Tuple1'), (923232.2323, 'Tuple4')]Input: [('Tuple1', 121), ('Tuple2', 125), ('Tuple1', 135), ('Tuple4', 478)]
7 min read
Python | Count tuples occurrence in list of tuples
Many a time while developing web and desktop products in Python, we use nested lists and have several queries about how to find the count of unique tuples. Let us see how to get the count of unique tuples in the given list of tuples. Below are some ways to achieve the above task. Method #1: Using Iteration C/C++ Code # Python code to count unique #
5 min read
Python | Combining tuples in list of tuples
Sometimes, we might have to perform certain problems related to tuples in which we need to segregate the tuple elements to combine with each element of complex tuple element( such as list ). This can have application in situations we need to combine values to form a whole. Let's discuss certain ways in which this can be performed. Method #1: Using
7 min read
Python | Convert string tuples to list tuples
Sometimes, while working with Python we can have a problem in which we have a list of records in form of tuples in stringified form and we desire to convert them to a list of tuples. This kind of problem can have its occurrence in the data science domain. Let's discuss certain ways in which this task can be performed. Method 1 (Using eval() + list
4 min read
Python | How to Concatenate tuples to nested tuples
Sometimes, while working with tuples, we can have a problem in which we need to convert individual records into a nested collection yet remaining as separate element. Usual addition of tuples, generally adds the contents and hence flattens the resultant container, this is usually undesired. Let's discuss certain ways in which this problem is solved
6 min read
Article Tags :
Practice Tags :