What is the purpose of the sorted() function when used with tuples?

What is the purpose of the sorted() function when used with tuples?

The sorted() function in Python is used to sort iterable objects such as lists, tuples, and strings. When used with tuples, it returns a new sorted list containing the elements of the tuple. Here are five examples demonstrating the purpose of the sorted() function when used with tuples:

  1. Sorting a Tuple of Numbers:
tuple_of_numbers = (4, 2, 7, 1, 5)
sorted_tuple = sorted(tuple_of_numbers)
print(sorted_tuple)  # Output: [1, 2, 4, 5, 7]
  1. Sorting a Tuple of Strings:
tuple_of_strings = ('banana', 'apple', 'orange', 'grape')
sorted_tuple = sorted(tuple_of_strings)
print(sorted_tuple)  # Output: ['apple', 'banana', 'grape', 'orange']
  1. Sorting a Tuple of Mixed Types:
mixed_tuple = (3, 'apple', 1.5, 'banana', 2.5)
sorted_tuple = sorted(mixed_tuple)
print(sorted_tuple)  # Output: [1.5, 2.5, 3, 'apple', 'banana']
  1. Sorting a Tuple of Tuples:
tuple_of_tuples = ((2, 'b'), (1, 'a'), (3, 'c'))
sorted_tuple = sorted(tuple_of_tuples)
print(sorted_tuple)  # Output: [(1, 'a'), (2, 'b'), (3, 'c')]
  1. Sorting a Tuple of Custom Objects:
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

people = (Person('Alice', 30), Person('Bob', 25), Person('Charlie', 35))
sorted_people = sorted(people, key=lambda x: x.age)
for person in sorted_people:
    print(person.name, person.age)
# Output:
# Bob 25
# Alice 30
# Charlie 35

In each example, the sorted() function takes a tuple as input and returns a new sorted list containing the elements of the tuple, according to the natural ordering of the elements or a custom sorting key if provided.

Did you find this article valuable?

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