python sort method

Estimated reading time: 1 minute

According to the  Python Organisation website, Python lists have a built-in list.sort() the method that modifies the list in-place.

mylist = [5, 2, 3, 1, 4]
[1, 2, 3, 4, 5]

This method only works for lists.

It also has a very similar method sorted() , which, unlike list.sort, can work on any iterable.

a= {'c':'1','b':'2','a':'3'}

['a', 'b', 'c']

Note that the sorted method only sorts the key value in the dictionary above.

Per parameters for the sorted() function are as follows:

sorted() can take a maximum of three parameters:

  • iterable – A sequence (stringtuplelist) or collection (setdictionaryfrozen set) or any other iterator.
  • reverse (Optional) – If, the sorted list is reversed (or sorted in descending order). Defaults to if not provided.
  • key (Optional) – A function that serves as a key for the sort comparison. Defaults to None.

Click how to sort lists in python to get a video tutorial on the above, which may help to explain the concepts further.