How do you sort a tuple in Python?

How do you sort a tuple in Python?

You can sort a tuple in Python using the sorted() function or by converting the tuple to a list, sorting it, and then converting it back to a tuple. Here are five examples demonstrating different ways to sort a tuple:

  1. Sorting a Tuple using sorted() function:
# Original tuple
my_tuple = (3, 1, 4, 1, 5, 9, 2, 6)

# Sorting the tuple
sorted_tuple = tuple(sorted(my_tuple))

print(sorted_tuple)  # Output: (1, 1, 2, 3, 4, 5, 6, 9)
  1. Sorting a Tuple of Strings using sorted() function:
# Original tuple
my_tuple = ('banana', 'apple', 'orange', 'grape')

# Sorting the tuple
sorted_tuple = tuple(sorted(my_tuple))

print(sorted_tuple)  # Output: ('apple', 'banana', 'grape', 'orange')
  1. Sorting a Tuple of Tuples based on the first element using sorted() function:
# Original tuple
my_tuple = ((3, 'c'), (1, 'a'), (4, 'd'), (2, 'b'))

# Sorting the tuple based on the first element of each inner tuple
sorted_tuple = tuple(sorted(my_tuple, key=lambda x: x[0]))

print(sorted_tuple)  # Output: ((1, 'a'), (2, 'b'), (3, 'c'), (4, 'd'))
  1. Sorting a Tuple of Tuples based on the second element using sorted() function:
# Original tuple
my_tuple = ((3, 'c'), (1, 'a'), (4, 'd'), (2, 'b'))

# Sorting the tuple based on the second element of each inner tuple
sorted_tuple = tuple(sorted(my_tuple, key=lambda x: x[1]))

print(sorted_tuple)  # Output: ((1, 'a'), (2, 'b'), (3, 'c'), (4, 'd'))
  1. Sorting a Tuple of Tuples based on the sum of elements using sorted() function:
# Original tuple
my_tuple = ((3, 1), (1, 4), (4, 1), (2, 5))

# Sorting the tuple based on the sum of elements in each inner tuple
sorted_tuple = tuple(sorted(my_tuple, key=lambda x: sum(x)))

print(sorted_tuple)  # Output: ((1, 4), (3, 1), (4, 1), (2, 5))

These examples demonstrate different ways to sort tuples in Python based on different criteria such as element values, tuple contents, or custom sorting functions.

Did you find this article valuable?

Support LingarajTechhub All About Programming by becoming a sponsor. Any amount is appreciated!