The sorted()
function is used to get a sorted list from the elements of a given iterable.
sorted(iterable, reverse = False, key = None)
copy
iterable |
The iterable containing the elements to be sorted |
reverse |
An optional boolean value(True or False ) indicating whether to sort the elements in reverse order. It defaults to False . |
key |
An optional parameter representing a function to be used as the criteria for sorting. |
The function returns a list containing the sorted elements of the given iterable.
By default the function sorts the elements in ascending order i.e from smallest to largest, if we specify the optional reverse
argument as True
, the elements will be sorted in descending order.
Example with a list
In cases where the iterable to be sorted is a list, as in above, you can use the sort() method to sort the list in place. This returns the original list with the elements sorted , unlike the sorted() function which returns an entirely new list.
Example with tuples
Sorting in reverse
By specifying the reverse
argument as True
, the elements will be sorted in reverse order.
Sorting keys
The optional argument, key
,can be used to specify the sorting criteria. The key is typically a function which takes a single argument and gets called on each element in the iterable prior to making comparisons, the returned values are used instead of the actual elements. For example to sort items in an iterable according to their length, we can pass the len()
function as the key.
The following example uses the abs() function as the key to sort integers in a list based on their absolute values rather than their natural order.
Lambda functions are incredibly versatile and they can be really useful in creating short and frexible one-line functions that can be passed as keys to sorted()
and similar functions.
Conclusion
You should use the sorted function to quickly get a list of sorted elements from an iterable.
The performance of the sorted()
function is quite fast and efficient. It uses the Timsort algorithm which is a combination of insertion sort and merge sort. The Timsort algorithm is very efficient in sorting already partially sorted data.