Skip to content

Python sort tuple | Order Example

  • by

You can sort the tuple by using the built-in function sorted() or sort() in Python. sorted() returns the sorted sequence. If you want to sort a list in place then use list.sort().

Examples of sorting tuple in Python

let’s see the example of using multiple methods to sort a tuple in python.

Use of sorted() method

The sorted () function will sort a tuple and returns a tuple with the elements in a sorted manner, without modifying the original sequence ( Will create a new tuple). See below example of it:-

tup = [('lucky', '18.265'), ('nikhil', '14.107'), ('akash', '24.541'),
       ('anand', '4.256'), ('gaurav', '10.365')]
print(sorted(tup))


Output:

[(‘akash’, ‘24.541’), (‘anand’, ‘4.256’), (‘gaurav’, ‘10.365’), (‘lucky’, ‘18.265’), (‘nikhil’, ‘14.107’)]

In-place way of sorting using sort():

While sorting a tuple element order via sort() function the actual content of the tuple is changed, while in the sorted() function the content of the original tuple remained the same.

tup = [('lucky', '18.265'), ('nikhil', '14.107'), ('akash', '24.541'),
       ('anand', '4.256'), ('gaurav', '10.365')]

# Sorting a tuple
tup.sort()
print(tup)

Output:

[(‘akash’, ‘24.541’), (‘anand’, ‘4.256’), (‘gaurav’, ‘10.365’), (‘lucky’, ‘18.265’), (‘nikhil’, ‘14.107’)]

Q: How to Sort Tuples in Increasing Order by any key?

Answer: You need to sort them according to any given key. So you have to use the 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.

Input: A = [(2, 55), (1, 20), (4, 40), (2, 30)] 
            k = 0
Output: [(1, 20), (2, 30), (2, 55), (4, 40)]

Example of Increasing Sorted order using the 0th index key.

def data(n):
return n[k]


def tuplesort(tup):
return sorted(tup, key=data)


# Driver code
a = [(230, 456, 120), (205, 414, 39), (89, 410, 213)]
k = int(input("Enter the Index ::>"))
print("Sorted:"),
print(tuplesort(a))

Output:

Python sort tuple Order Example

Do comment if you have any doubts and suggestions on this tutorial.

Note:
IDE: PyCharm 2020.1.1 (Community Edition)
macOS 10.15.4
Python 3.7
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Your email address will not be published. Required fields are marked *