You can use Python sorted()
function to do sort operation objects. The method sort differs from the method sorted: sort()
method is applied on the list, sorted()
return a new sorted list from the items in iterable.
The sort()
method sorts the already existing list, no return value. The sorted method returns a new list, rather than operations carried out in the original list.
It returns a new sorted list from the items in iterable.
sorted example
The following example demonstrates the use of sorted:
>>> a = [5,7,6,3,4,1,2]
>>> b = sorted(a)
>>> a
[5, 7, 6, 3, 4, 1, 2]
>>> b
[1, 2, 3, 4, 5, 6, 7]
>>>
To do an ascending sort call the sorted() function. It returns a new sorted list:
>>> sorted([5, 2, 3, 1, 4])
[1, 2, 3, 4, 5]
This is different than sort, which uses an existing list.
>>> a = [5, 2, 3, 1, 4]
>>> a.sort()
>>> a
[1, 2, 3, 4, 5]
Top comments (1)
I feel like this post falls really short and should at least include the
key=
documentation forsorted
that makes it powerful: the ability to sort objects how you want.