DEV Community

toebes618
toebes618

Posted on

Sorted() with Python

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)

Collapse
 
mburszley profile image
Maximilian Burszley

I feel like this post falls really short and should at least include the key= documentation for sorted that makes it powerful: the ability to sort objects how you want.

>>> import pprint
>>> a = [
>>>   {'id': 5},
>>>   {'id': 4},
>>>   {'id': 3}
>>> ]
>>> sorted_a = sorted(a, key=lambda x: x['id'])
>>> pprint.pprint(sorted_a, width=1)
[{'id': 3},
 {'id': 4},
 {'id': 5}]