To sort a tuple in Python, you can’t directly modify it because tuples are immutable. However, you can create a sorted version of the tuple using the built-in sorted() function, which returns a new sorted list. If needed, you can convert the sorted list back into a tuple using tuple().
Here’s an example:
python
my_tuple = (5, 2, 8, 1)
sorted_tuple = tuple(sorted(my_tuple))
print(sorted_tuple) # Output: (1, 2, 5, 8)
You can also customize the sorting order using the key and reverse parameters in sorted(). For example, use reverse=True for descending order.