# Python sorted method

The sorted method is used for sorting operations, such as number, string order of the list etc.

If sorting a list in python, you can use the List class member function `sort()`, which operates on the original space, modifying the list itself and not returning a copy. The grammar reads as follows.

``````L.sort(cmp=None, key=None, reverse=False)
``````

The sorted function is much more powerful than the `sort()` function, which can only sort lists, and `sorted()` can sort all iteratable types and return new sorted lists.

Related course: Complete Python Programming Course & Exercises

## Sorted Syntax

``````sorted(iterable[, cmp[, key[, reverse]]])
``````

Description of parameters.

• iterable -- Iterable objects.

• cmp -- The function of comparison (which has been completely removed from python3), this function has two arguments, the values of which are taken from iteratable objects, the rules that this function must obey are, greater than returns 1, less than returns -1, equal to returns 0.

• key -- the element that is primarily used for comparison (provided by python2.4 onwards, previously using cmp), with only one argument, the argument of the specific function is taken from the iteratable object, specifying an element in the iteratable object to be sorted. This function will be called before each element is compared.

• reverse -- sequencing rule, reverse = True descending, reverse = False ascending (default).

return value

• Returns the reordered list.

## Sorted Example

The following example shows how sorted can be used.

``````>>> a = [1,2,1,4,3,5]
>>> a.sort()
>>> a
[1, 1, 2, 3, 4, 5]
>>> a = [1,2,1,4,3,5]
>>> sorted(a)
[1, 1, 2, 3, 4, 5]
>>> a
[1, 2, 1, 4, 3, 5]
``````

More examples:

``````>> a = [5,7,6,3,4,1,2]
>> b = sorted(a) # Retain original list
>> a [5, 7, 6, 3, 4, 1, 2]
>> b[1, 2, 3, 4, 5, 6, 7]
>> L=[('b',2),('a',1),('c',3),('d',4)]
>>
>> sorted(L, cmp=lambda x,y:cmp(x,y)) # Utilize cmp function [('a', 1), ('b', 2), ('c', 3), ('d', 4)]
>> sorted(L, key=lambda x:x) # Utilize key[('a', 1), ('b', 2), ('c', 3), ('d', 4)]
`````` reverse sorted Sorted returning a list in reverse order

``````>>> sorted(list1,reverse = True)
[('sara', 80), ('mary', 90), ('lily', 95), ('david', 90)]
``````

sorted with cmp Sorted with your own comparison function

``````>>> list1 = [('david', 90), ('mary',90), ('sara',80),('lily',95)]
>>> sorted(list1,cmp = lambda x,y: cmp(x,y))
[('david', 90), ('lily', 95), ('mary', 90), ('sara', 80)]
>>> sorted(list1,cmp = lambda x,y: cmp(x,y))
[('sara', 80), ('david', 90), ('mary', 90), ('lily', 95)]
``````

sorted with key Returns a sorted list using key

``````>>> list1 = [('david', 90), ('mary',90), ('sara',80),('lily',95)]
>>> sorted(list1,key = lambda list1: list1)
[('david', 90), ('lily', 95), ('mary', 90), ('sara', 80)]
>>> sorted(list1,key = lambda list1: list1)
[('sara', 80), ('david', 90), ('mary', 90), ('lily', 95)]
``````