This guide deals with the Python sorted function and it’s uses, complete with several examples.

The python sorted function can be used to sort sequences of values in all kinds of ways. For instance, it can sort a list of strings in alphabetical order, or a list of numerical values in ascending or descending order.

Syntax

The sorted function takes three parameters in total. Only the first is compulsory, with the other two being optional.

sorted(iterable, key=None, reverse=False)

Parameters

  • iterable: The iterable to be sorted.
  • Key: The key function allows us to change the way the sorted() function works. Assigning it to the len() function for instance, makes the sorted function sort by length. Default function is None.
  • reverse: If set to True, the sorted function will sort in reverse. Default is False.

Do not confuse the sorted function with the sort function for lists. sorted returns a new object, whereas sort changes the list itself.


Example set 1

>>> X = [4,5,7,3,1]
>>> sorted(X)
[1, 3, 4, 5, 7]

>>> X = "String"
>>> sorted(X)
['S', 'g', 'i', 'n', 'r', 't']

>>> X = ["a", "c", "z", "b"]
>>> sorted(X)
['a', 'b', 'c', 'z']

Example Set 2

Here we’ll be using the len function in place of key. This causes all the elements in the sequence to be sorted according to their length. By default, it’s sorted in ascending order. Use, reverse to sort in descending order.

>>> X = ["Apple", "Grapes", "Oranges"]
>>> sorted(X, key = len)
['Apple', 'Grapes', 'Oranges']

Example Set 3

Some examples of using the reverse = True setting.

>>> X = ["a", "c", "z", "b"]
>>> sorted(X , reverse = True)
['z', 'c', 'b', 'a']

>>> X = ["Apple", "Grapes", "Oranges"]
>>> sorted(X, reverse = True)
['Oranges', 'Grapes', 'Apple']

This marks the end of the Python sorted Function Article. Any suggestions or contributions for CodersLegacy are more than welcome. Any questions can be asked in the comments section below.

Here’s a link back to the main Python Built-in Functions page.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments