Monday, January 27, 2025
HomeProgrammingHow to Sort Tuple in Python?

How to Sort Tuple in Python?

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().

See also  How do you create a dictionary in Java? [closed]

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.

RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Recent Comments

0
Would love your thoughts, please comment.x
()
x