sort tuple in python

How to Sort a Tuple in Python (+Hacks)

To sort a tuple in Python, there are predefined functions that you can easily use. Let’s avoid exaggeration and get straight to the point.

Sorted() Function in Python

The sorted() function returns a sorted list of what you give it as an iterable object.

You can choose between ascending or descending order.

There are two different approaches to sorting strings and numbers:

  • Strings are sorted by their first letter
  • Numbers are sorted by their values.

So we can use this function to sort a string or numerical tuple.

Sorted() function accepts 3 parameters – as sorted(iterable, key=key, reverse=reverse):

  • iterable: (Required) – The sequence to sort, such as list, dictionary, tuple, etc.
  • key: (Optional) – A function to execute in order to sort by the way you want, default is None.
  • reverse: (Optional) – True/False where True tells it to sort them descending and False to sort them ascending.

Sort a Tuple of Numbers in Python

Let’s say we have a tuple of numbers like old_tuple = (1, 8, 6, 3, 9, 7, 2). Now we want to sort this tuple.

Sorting the tuple of numbers in ascending order:

old_tuple = (1, 8, 6, 3, 9, 7, 2)
ascending_sorted = sorted(old_tuple)
print(ascending_sorted) # 👉️ [1, 2, 3, 6, 7, 8, 9]

# -----------------
# Optional: sorted function returns a list,
# if you want a tuple instead, you can
# call the tuple function to 
# convert the list to a tuple again.
# for example: new_tuple = tuple(ascending_sorted)

Sorting the tuple of numbers in descending order:

old_tuple = (1, 8, 6, 3, 9, 7, 2)
descending_sorted_tuple = sorted(old_tuple, reverse=True)
print(descending_sorted_tuple) # 👉️ [9, 8, 7, 6, 3, 2, 1]

# -----------------
# Optional: sorted function returns a list,
# if you want a tuple instead, you can
# call the tuple function to 
# convert the list to a tuple again.
# for example: new_tuple = tuple(ascending_sorted)

Sort a Tuple of Strings in Python

Sorted function works for strings as well as for numbers. with the difference that it sorts the strings alphabetically.

Let’s say that we have a tuple of strings like old_tuple = ('a', 'c', 'b', 'z', 'y') and we want this tuple to be sorted.

Sorting the tuple by string values in ascending order:

old_tuple = ('a', 'c', 'b', 'z', 'y')
ascending_sorted = sorted(old_tuple)
print(ascending_sorted) # 👉️ ['a', 'b', 'c', 'y', 'z']

# -----------------
# Optional: sorted function returns a list,
# if you want a tuple instead, you can
# call the tuple function to 
# convert the list to a tuple again.
# for example: new_tuple = tuple(ascending_sorted)

Sorting the tuple by string values in descending order:

old_tuple = ('a', 'c', 'b', 'z', 'y')
descending_sorted = sorted(old_tuple, reverse=True)
print(descending_sorted) # 👉️ ['z', 'y', 'c', 'b', 'a']

# -----------------
# Optional: sorted function returns a list,
# if you want a tuple instead, you can
# call the tuple function to 
# convert the list to a tuple again.
# for example: new_tuple = tuple(descending_sorted)

Sort a tuple/list of tuples/lists by the element at a given index

What would happen if our list or tuple did not contain only one element? For example, it contained 2 elements or even more, 3 or 4 elements and we wanted to sort this list or tuple based on its third element?

Let’s check together how this is possible.

If you remember, we said a little earlier that the key in the sort function accepts a function that determines the basis of our sorting. In simpler words, we can pass a function to the key parameter of Sorted() function and define a criteria for sorting.

We can pass this function as a lambda expression. Let’s check how it is possible:

old_values = [(100, 'c', 'b', 75), (25, 'a', 'r', 62), (87, 'h', 'gf', 65)]
# -----------------
# sorting based on third element 
# (element at index 2)
# *remember, python indexes starts from 0
sorted_values = sorted(old_tuple, key=lambda tup: tup[2])
print(sorted_values) 
# 👉️ [(100, 'c', 'b', 75), (87, 'h', 'gf', 65), (25, 'a', 'r', 62)]

# -----------------
# Hint: for a descending sort, pass `reverse=True` to the sorted() function.

Indices in Python start from zero. Therefore, to sort based on the value of the third element, we must give index 2 to the lambda expression. Also, to sort based on the value of the fourth element, we must give it index 3.

There is no limit on the type of the function that you give to the key as a lambda expression. For example, you can use len(), a function that returns the length of a string. And, sort the tuple by the length of elements.

example_tuple = ('abcd', 'abd', 'a', 'ab')

sorted_tuple = tuple(
    sorted(example_tuple, key=lambda s: len(s), reverse=True)
)
print(sorted_tuple)  
# 👉️ ('abcd', 'abd', 'ab', 'a')

Sort a Tuple by Multiple Elements (+Priority)

But it is not always the case that we want to sort a tuple based on only one element. Sometimes we may come across a situation where we want to sort a tuple based on 2 elements or even more. What should be done in such cases?

In such cases, we can use a tuple as a lambda expression. Consider the following example:

my_tuple = [(1,2,3),(1,2,1),(1,1,4)]
sorted_tuple = sorted(my_tuple, key=lambda tup: (tup[1],tup[2]))
print(sorted_tuple) 
# 👉️ [(1, 1, 4), (1, 2, 1), (1, 2, 3)]

As you can see, for first sorting, it considers the element in index number 1 and sorts based on it, and then compares the element in index number 2 and completes the sort.

Sorting in Place

Sometimes there is no need to create a new variable and store the sorted values in it, and you want to sort the existing tuple on the fly.
For this purpose, you can call the Sort() function on the tuple itself.

old_tuple = ('a', 'c', 'b', 'z', 'y')
old_tuple.sort(reverse=True)
print(old_tuple) 
# 👉️ ['z', 'y', 'c', 'b', 'a']