Use sorted() with reverse=True
In this step, we will delve deeper into using the sorted()
function with the reverse=True
parameter to sort tuples in descending order. We'll explore different scenarios and demonstrate how to apply this technique effectively.
Let's revisit the tuple we've been working with:
my_tuple = (5, 2, 8, 1, 9)
print("Original tuple:", my_tuple)
Make sure this is in your tuple_sort.py
file. If not, add it now.
As we learned in the first step, the sorted()
function can be used to sort the elements of a tuple. When we set reverse=True
, it sorts the elements in descending order. Let's use this to sort our tuple and print the result:
my_tuple = (5, 2, 8, 1, 9)
print("Original tuple:", my_tuple)
sorted_tuple = tuple(sorted(my_tuple, reverse=True))
print("Sorted tuple (descending):", sorted_tuple)
Now, run the script:
python tuple_sort.py
You should see the following output:
Original tuple: (5, 2, 8, 1, 9)
Sorted tuple (descending): (9, 8, 5, 2, 1)
Now, let's consider a different scenario. Suppose we have a tuple of strings:
string_tuple = ("apple", "banana", "cherry", "date")
print("Original string tuple:", string_tuple)
Add this to your tuple_sort.py
file.
We can also sort this tuple in descending order using sorted()
with reverse=True
. When sorting strings, Python uses lexicographical order (i.e., dictionary order).
Add the following lines to your script:
string_tuple = ("apple", "banana", "cherry", "date")
print("Original string tuple:", string_tuple)
sorted_string_tuple = tuple(sorted(string_tuple, reverse=True))
print("Sorted string tuple (descending):", sorted_string_tuple)
Run the script again:
python tuple_sort.py
You should see the following output:
Original string tuple: ('apple', 'banana', 'cherry', 'date')
Sorted string tuple (descending): ('date', 'cherry', 'banana', 'apple')
As you can see, the strings are sorted in reverse alphabetical order.
In summary, the sorted()
function with reverse=True
provides a flexible way to sort tuples (and other iterables) in descending order, whether they contain numbers or strings. This is a fundamental technique for data manipulation in Python.