Python Program to Sort a Tuple By Values


In this article, we will be discussing how to sort a tuple by values in Python. A tuple is a data structure that is similar to a list, but it is immutable, meaning that once it is created, we cannot change the values of the elements within it.

Example

Following is an example to create a tuple –

tple = ("Hello", "world", "hi")
print(tple)

Output

(“Hello”, “world”, “hi”)

Ordered, immutable triple items can have multiple values. An index of [0] is assigned to the first item in a triple, [1] to the second, and so on.

When we refer to a tuple as being sorted, we imply that the elements are put in a certain order.

Due to their immutability, tuples cannot have any of their components changed, added, or removed once they have been created.

Example

Duplicate values are permitted in tuples −

tple = ("apple", "banana", "cherry", "apple", "cherry")
print(tple)

Output

(‘apple’, ‘banana’, ‘cherry’, ‘apple’, ‘cherry’

Keys and values in tuples

Keys and values do not often exist as a pair in a tuple, since they are only used to hold single instances of any given object. To make a tuple containing keys and values, on the other hand, we must create tuples that are nested inside of one another.

The first value in each tuple will thus represent its key, and the second value will represent its value.

Example

ListOfTuples = ((1, 4), (3, 5), (4, 5), (5, 6))

In the code line above, two tuples are enclosed within one tuple; as a result, the first item of the outer list, for example, is a tuple with two values. Here, the tuple's key is represented by value 1 and its data value by value 4, respectively.

We will use indexing to access the inner tuple elements as well as the keys and values as we are aware that indexing may be used to access a tuple now.

print(ListOfTuples[0][0])

This will output the outer list's first tuple's key that is located. But what if we are unaware of how many elements the outer list contains? We run the danger of encountering an index out-of-range error, which indicates that we are attempting to access an element that is not present in the tuple, if we use indexing to try to reach the inner elements in such a scenario.

Using the len() function

To solve this issue, we can use the len function to determine how many items there are in the outer list before using it to output the keys and values for just those components.

Note that the values are actually the second element of the nested list, so if we have to sort the tuple list, we have to actually compare the values that are the second elements of all the tuples inside the list and only after comparing all those values we will be able to sort them.

As it requires looking into the values, again and again, we will be needing the nested for loop. The algorithm for the same will be as follows.

Algorithm

  • Create a tuple list with the element being tuple of two values the first being the key and the second being the data element.

  • Print the tuple list before sorting.

  • Use the ‘for loop’ to iterate over the elements of the list from 0 to the length of that list.

  • Use another nested loop which will run from 0 to one less than the length of the list.

  • Now check whether the value part of the current element is greater than that of the value part of the next element.

  • If yes, swap both elements, tuples.

  • If no, continue to the next element.

Example

tupleList = [(2, 5), (1, 3), (17, 27), (0, 5), (4, 1)]
print("The elements of tuple list before sorting by values are : ")
for item in tupleList:
   print(f"Key : {item[0]} Value : {item[1]}")
for i in range(len(tupleList)):
   for j in range(len(tupleList) - 1):
      if tupleList[j][1] > tupleList[j+1][1]:
         tupleList[j], tupleList[j+1] = tupleList[j+1], tupleList[j]
print("The elements of tuple list after sorting by values are : ")
for item in tupleList:
   print(f"Key : {item[0]} Value : {item[1]}")

Output

The elements of tuple list before sorting by values are :
Key : 2 Value : 5
Key : 1 Value : 3
Key : 17 Value : 27
Key : 0 Value : 5
Key : 4 Value : 1
The elements of tuple list after sorting by values are :
Key : 4 Value : 1
Key : 1 Value : 3
Key : 2 Value : 5
Key : 0 Value : 5
Key : 17 Value : 27

Conclusion

In this article, we saw the use of nested loops to sort a tuple by its values. Alternatively, we can also make use of the sort method with a lambda function to write a one-line solution for the same problem.

TupleWithKeys.sort(key=lambda item: item[1])

The method above is actually the most pythonic way to solve the problem.

Updated on: 17-Feb-2023

119 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements