Tuple is a collection of elements. It is enclosed in parentheses ‘()’ and elements are separated using ‘,’. It is immutable in nature and can contain elements of different data types. Sorting a tuple refers to arranging the elements in a proper order.
In python one can use the built in function or design their own algorithm to sort a tuple.
Why is there a need to sort tuple
Sorting a tuple can make it easier to read, search, and compare data, as well as improving the efficiency of algorithms that operate on the data.
- Ordering– Sorting can help you display elements in an arranged manner or in a specific order.
- Searching- It becomes easier to search for an element when the tuple is sorted.
- Output formatting– If you want to output your tuple in a specific order, sorting it in the required way helps you in doing that.
- Performance– Sorting can improve the efficiency and optimality of certain algorithms. For example- Binary Search Algorithm which works efficiently and faster when the tuple is sorted.
There are Three main method to sort a tuple in python
- Design your own Algorithm
- Using built-in sorted() method
- Using the built-in sort method
Let’s dive in detail for more information:
1. Design your own algorithm
One can design their own algorithm and use it to sort a tuple in python. There are several sorting algorithms available to do so.
One such example is merge sort.
Algorithm
- If the list has only one element, it is already sorted, so return the list.
- Split the list into two halves, a left half and a right half.
- Recursively call merge sort on the left half and the right half.
- Merge the sorted left half and right half into a single sorted list:
- Initialize an empty list called result.
- Initialize two pointers, one for the left half and one for the right half, both pointing to the beginning of their respective lists.
- Compare the first elements of the left and right halves, and add the smaller one to result.
- Move the pointer for the smaller element to the next element in its list.
- Repeat steps c and d until one of the pointers reaches the end of its list.
- Add the remaining elements of the other list to result.
- Return result.
Code:
def merge(left, right): #helper function to merge two sorted arrays
result = []
i, j = 0, 0 #two pointers to move in both the arrays
while i < len(left) and j < len(right):
if left[i] <= right[j]: #if the element in left array is larger
result.append(left[i]) #append it first
i += 1
else:
result.append(right[j]) #else the element from the right array
j += 1
#appending up the remaining elements
result += left[i:]
result += right[j:]
return result
def mergesort(lst):
#this function recursively splits the tuple into two parts and then calls
#merge function to merge the sorted tuples
if len(lst) <= 1:
return lst
mid = len(lst) // 2
left = lst[:mid]
right = lst[mid:]
left = mergesort(left)
right = mergesort(right)
return list(merge(left, right))
#driver code
t = (3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5) #initializing the tuple
# sort the tuple using mergesort
sorted_t = tuple(mergesort(list(t)))
# print the sorted tuple
print(sorted_t)
Output:
(1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9)
Explanation:
- In the driver code firstly the tuple is initialized.
- Then the mergesort function is called with the tuple as parameter
- The mergesort recursively splits the tuple in two parts and calls the helper function to merge the sorted tuple.
- This function takes two sorted tuples and merges them in a single tuple
2. Using the built in sorted() method
This method sorts the tuple and returns a new sorted list. As the tuples are immutable in nature this method comes in handy as it does not sort in place but returns a new list instead.
It takes three parameters out of which two are optional.
- iterable – Any sequence that can be sorted.
- Key – It is an optional parameter which defines the basis on which the tuple should be sorted.
- Reverse- when this parameter is set true, it sorts the tuple but in reverse or in descending order.
This function returns a list so make sure to convert the output back into a tuple.
Code:
t = (3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5) #initializing the tuple
#calling the sorted method and performing explicit type conversion
sorted_t = tuple(sorted(t))
# print the sorted tuple
print(sorted_t)
Output:
(1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9)
Explanation:
1.Initialize the tuple.
2. Pass the tuple to the sorted method and explicitly convert the output in a tuple and then store it in another variable.
3.Print the sorted array.
3. Using the built in sort() method:
This method is used to sort a list in place, but tuples are immutable in nature so the tuple must be converted to a list first and then it can be sorted using this function.
It can take two extra parameters:
- Key – It is an optional parameter which defines the basis on which the list should be sorted.
- Reverse- when this parameter is set true, it sorts the list but in reverse or in descending order.
This function will not sort a tuple as they are immutable , so make sure to convert your tuple into a list first.
Code:
example = (89, 47, 9, 2, 34, 72) #Initializing the tuple
example = list(example) # explicitly convert the tuple into a list
example.sort() #the tuple is explicitly converted into a list and then the sort method is called
print(example) #printing the sorted tuple which is now list
Output:
[2, 9, 34, 47, 72, 89]
Explanation:
- Initialize the tuple.
- Convert the tuple into a list
- Pass the converted list to the sort method.
- Print the sorted list.
The best approach to sort a tuple in python:
The best method is to use the built in method present in python because:
- It is implemented in a very optimal and efficient way.
- It will save you from writing extra code.
- It helps you sort the tuple in any order and based on a specific criterion, like the key value.
- No need to convert your tuple into a list.
Sample Problem
Problem 1
Given a tuple representing marks of students in a class- ( 89, 10, 4, 67, 42, 11, 17, 2) , Write an algorithm to arrange their marks in ascending order.
Code:
def merge(left, right): #helper function to merge two sorted arrays
result = []
i, j = 0, 0 #two pointers to move in both the arrays
while i < len(left) and j < len(right):
if left[i] <= right[j]: #if the element in left array is larger
result.append(left[i]) #append it first
i += 1
else:
result.append(right[j]) #else the element from the right array
j += 1
#appending up the remaining elements
result += left[i:]
result += right[j:]
return result
def mergesort(lst):
#this function recursively splits the tuple into two parts and then calls
#merge function to merge the sorted tuples
if len(lst) <= 1:
return lst
mid = len(lst) // 2
left = lst[:mid]
right = lst[mid:]
left = mergesort(left)
right = mergesort(right)
return list(merge(left, right))
#driver code
t = ( 89, 10, 4, 67, 42, 11, 17, 2) #initializing the tuple
# sort the tuple using mergesort
sorted_t = tuple(mergesort(list(t)))
# print the sorted tuple
print(sorted_t)
Output:
(2, 4, 10, 11, 17, 42, 67, 89)
Problem 2
Write a python code to sort the given tuple representing the marks of students in ascending order – ( 89, 10, 4, 67, 42, 11, 17, 2)
Solution-
1.Initialize the tuple.
2. Pass the tuple to the sorted method and explicitly convert the output in a tuple and then store it in another variable.
3.Print the sorted array.
Code-
t = ( 89, 10, 4, 67, 42, 11, 17, 2) #initializing the tuple
#calling the sorted method and performing explicit type conversion
sorted_t = tuple(sorted(t))
# print the sorted tuple
print(sorted_t)
Output-
(2, 4, 10, 11, 17, 42, 67, 89)
Problem 3
Given the marks of students, sort them according to their rank in class :- ( 89, 10, 4, 67, 42, 11, 17, 2), in descending order.
Solution-
1.Initialize the tuple.
2. Pass the tuple to the sorted method and explicitly convert the output in a tuple and then store it in another variable.
3.Print the sorted array.
Code:
t = ( 89, 10, 4, 67, 42, 11, 17, 2) #initializing the tuple
#calling the sorted method and performing explicit type conversion
sorted_t = tuple(sorted(t, reverse= True))
# print the sorted tuple
print(sorted_t)
Output
(89, 67, 42, 17, 11, 10, 4, 2)
Problem 4
Given the height of students in cm – (54, 63, 72, 60, 59, 65), arrange them in order with the tallest in the first place without using any extra memory .
Solution
- Initialize the tuple.
- Convert the tuple into a list
- Pass the converted list to the sort method.
- Print the sorted list.
Code:
example = (54, 63, 72, 60, 59, 65) #Initializing the tuple
example = list(example)
example.sort() #the tuple is explicitly converted into a list
#and then the sort method is called
print(example) #printing the sorted tuple which is now list
Output:
[54, 59, 60, 63, 65, 72]
Problem 5- Given the names of students-(“jagriti”, “Soumya”, “Tanu”, “Rahul”, “param”), arrange them on the basis of their lengths.
Solution:
- Initialize the tuple.
- Pass the tuple to the sorted method ,along with the key parameter and len as value.
- Explicitly convert the output in a tuple and then store it in another variable.
- Print the sorted tuple.
Code:
example = ( 'jagriti', 'Soumya', 'Tanu', 'Rahul', 'param')#Initializing the tuple
#calling the sorted method along with the key parameter with len as value
#and performing explicit type conversion
sorted_example = tuple(sorted(example, key = len))
print(sorted_example)
Output:
('Tanu', 'Rahul', 'param', 'Soumya', 'jagriti')
Conclusion
Tuple is a data structure used to store a collection of objects in python. It is ordered and immutable in nature i.e. once a tuple is created it’s values cannot be updated.
To sort a tuple one may not need to design their algorithm and write extra code every time but can simply use the sorted method of python to do so.