Python sorted(tuple) function


The sorted() function in Python is used to return a new sorted list from the items in an iterable, such as a tuple. This function can sort the elements in ascending or descending order based on your specifications.

Syntax

sorted(iterable[, key=None[, reverse=False]])
  • iterable: The iterable (like a tuple) you want to sort.
  • key (optional): A function that serves as a key for the sort comparison. This can be used to customize the sorting order based on certain criteria.
  • reverse (optional): A boolean value. If set to True, the list is sorted in descending order. The default is False, which means sorting in ascending order.

Return Value

  • The sorted() function returns a new list containing all items from the iterable in sorted order. It does not modify the original iterable.

Example

Here are some examples to illustrate how sorted() works with tuples:

1. Basic Example with Numeric Value:

# Example tuple with numbers my_tuple = (5, 3, 1, 4, 2) # Sorting the tuple sorted_tuple = sorted(my_tuple) print(sorted_tuple) # Output: [1, 2, 3, 4, 5]

2. Sorting Strings

# Example tuple with strings string_tuple = ('banana', 'apple', 'cherry') # Sorting the tuple sorted_strings = sorted(string_tuple) print(sorted_strings) # Output: ['apple', 'banana', 'cherry']

3. Sorting in Descending Order

# Example tuple with numbers my_tuple = (5, 3, 1, 4, 2) # Sorting in descending order sorted_descending = sorted(my_tuple, reverse=True) print(sorted_descending) # Output: [5, 4, 3, 2, 1]

4. Using a Key Function

# Example tuple with strings mixed_tuple = ('apple', 'banana', 'cherry', 'date') # Sorting by length of the strings sorted_by_length = sorted(mixed_tuple, key=len) print(sorted_by_length) # Output: ['apple', 'date', 'banana', 'cherry']

Use Cases

  • Sorting Data: Useful for organizing data in a desired order, whether for display or further processing.
  • Custom Sorting: The key parameter allows for sorting based on specific attributes or criteria, enhancing flexibility.
  • Non-destructive Sorting: Since it returns a new list, the original tuple remains unchanged, making it safe for various applications.

Summary

The sorted(tuple) function is a versatile and powerful built-in function in Python that enables sorting of iterable elements, providing options for customization through the key and reverse parameters. It is an essential tool for data manipulation and organization in programming.