- Published on
Sorting Tuples in Python
In python tuples are a collection of objects which are ordered and immutable. Tuples are sequences, just like lists. Tuples are much similar to lists. The only differences between tuples and lists are, the tuples cannot be changed unlike lists and tuples use parentheses, whereas lists use square brackets.
For example, here is a tuple of the numbers from 1 up to 5
nums = (1, 2, 3, 4)
Since tuples cannot be changed, the only way to sort a tuple is to create a new tuple with the desired order of items. In Order to sort tuples in python we need to Pass the tuple to the sorted()
function. The function will return a new sorted list from the items in the tuple. You can pass the list you get from the sorted function to the tuple()
class to convert it back to a tuple.
The sorted()
function takes an iterable like a sequence (string,tuple,list) or collection (set,dictionary) and returns a new sorted list from the items in the iterable.
# ✅ sort a tuple containing numbers
my_tuple_1 = (3, 1, 2, 8, 10)
sorted_tuple_1 = tuple(sorted(my_tuple_1))
print(sorted_tuple_1) # 👉️ [1, 2, 3, 8, 10]
# ✅ sort a tuple containing strings
my_tuple_2 = ('d', 'b', 'c', 'a')
sorted_tuple_2 = tuple(sorted(my_tuple_2))
print(sorted_tuple_2) # 👉️ ['a', 'b', 'c', 'd']
The sorted()
function takes an optional key
argument that can be used to sort by different criteria so based on the returned value of the key function, you can sort the given iterable.
# ✅ sort a list of tuples by second element in each tuple
my_list_of_tuples = [('a', 100), ('b', 50), ('c', 75)]
result = sorted(my_list_of_tuples, key=lambda t: t[1])
print(result) # 👉️ [('b', 50), ('c', 75), ('a', 100)]
In the above example we are sort a list tuple by second element in each tuple
A list also has the sort()
method which performs the same way as the sorted() function. The difference is that the sort()
method doesn't return any value but mutates the original list.
The sorted function also takes a third parameter as a boolean optional argument. If we set reverse = True sorts the iterable in the descending order.
my_tuple_1 = (3, 1, 2, 8, 10)
sorted_tuple_1 = tuple(sorted(my_tuple_1, reverse=True))
print(sorted_tuple_1) # 👉️ (10, 8, 3, 2, 1)
my_tuple_2 = ('abc', 'abcd', 'a', 'ab',)
sorted_tuple_2 = tuple(
sorted(my_tuple_2, key=lambda s: len(s), reverse=True)
)
print(sorted_tuple_2) # 👉️ ('abcd', 'abc', 'ab', 'a')
Conclusion
Sorting tuples in Python can be done easily with just a few lines of code. In this Article we learned how to sort a Tuple in Python using the sorted() function. With these techniques in mind, you can confidently sort your tuples in any Python project.