The sorted
function in Python is a built-in utility that returns a new list containing all items from an iterable, sorted in ascending order by default. It provides a convenient way to sort elements without modifying the original iterable, making it versatile for various data manipulation tasks.
sorted
Function WorksThe sorted
function can sort any iterable (such as lists, tuples, and strings) and returns a new list with the elements sorted.
**iterable**
: The iterable to be sorted (e.g., list, tuple, string).**key**
(optional): A function that takes an element and returns a value to be used for sorting. The default is None
, which means sorting is based on the elements' natural ordering.**reverse**
(optional): A boolean value indicating whether to sort in descending order. The default is False
, which sorts in ascending order.Output:
In this example, sorted
returns a new list with the numbers sorted in ascending order.
key
ParameterThe key
parameter allows you to specify a function to determine the sorting criteria.
Output:
Here, sorted
uses the length of each word for sorting, resulting in words arranged by length.
reverse
ParameterThe reverse
parameter allows you to sort in descending order.
Output:
In this example, sorted
returns a list sorted in descending order.
sorted
with sort
**sorted**
: Returns a new sorted list and does not modify the original iterable.
**sort**
: Modifies the list in place and does not return a new list.
Example Comparison:
Here, sorted
does not alter the original list, while sort
modifies the list in place.
Output:
In this example, sorted
sorts a list of tuples by the second element of each tuple (the fruit names).
Output:
Here, sorted
arranges the strings in alphabetical order.
Output:
In this example, sorted
orders students by their scores in descending order.
The sorted
function in Python is a powerful tool for sorting iterables and creating new lists in a specified order. It offers flexibility with its key
and reverse
parameters, making it suitable for a wide range of sorting tasks. Understanding how to use sorted
effectively can enhance your data manipulation capabilities and improve the efficiency of your Python programs.