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
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 toTrue
, the list is sorted in descending order. The default isFalse
, 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:
2. Sorting Strings
3. Sorting in Descending Order
4. Using a Key Function
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.