Sort Tuples in Python Using the Sorted() function

To sort tuples in Python, you can use the built-in sorted() function with a custom key parameter that specifies the element to sort by.


When working with tuples in Python, you may encounter the need to sort them based on certain criteria. Sorting tuples can be quite useful in various scenarios, such as when you have a list of tuples representing data points and you want to organize them in a specific order.

In Python, tuples are immutable sequences, which means that their elements cannot be changed once they are created. However, you can still sort tuples based on their elements using the sorted() function.

Here’s how you can sort tuples in Python:

Using the sorted() function

The sorted() function in Python can be used to sort any iterable object, including tuples. To sort a tuple, you can pass it as an argument to the sorted() function along with a custom key parameter that specifies the element to sort by.

# Define a list of tuples
data = [(3, 'apple'), (1, 'banana'), (2, 'orange')]

# Sort the list of tuples by the first element
sorted_data = sorted(data, key=lambda x: x[0])

print(sorted_data)

In this example, we have a list of tuples representing fruits and their corresponding numbers. By specifying key=lambda x: x[0], we are sorting the tuples based on the first element (the numbers) in ascending order. As a result, the output will be:

[(1, 'banana'), (2, 'orange'), (3, 'apple')]

Sorting in descending order

If you want to sort the tuples in descending order, you can simply add the reverse=True parameter to the sorted() function:

# Sort the list of tuples by the first element in descending order
sorted_data_desc = sorted(data, key=lambda x: x[0], reverse=True)

print(sorted_data_desc)

This will sort the tuples based on the first element in descending order.

Conclusion

Sorting tuples in Python is a simple task that can be accomplished using the sorted() function with a custom key parameter. By specifying the element to sort by, you can easily organize your tuples in the desired order. Experiment with different key functions to customize the sorting behavior based on your requirements.

Stephen Mclin
Stephen Mclin

Hey, I'm Steve; I write about Python and Django as if I'm teaching myself. CodingGear is sort of like my learning notes, but for all of us. Hope you'll love the content!

Articles: 90

Leave a Reply

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