Python sort tuple | Order Example

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 method 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 new tuple). See below example of it:-

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 elements 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.

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 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.

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

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.