108 of 151 menu

The sorted function

The sorted function returns a sorted list of iterables - a list, a tuple, a set, a dictionary. By default, the function sorts the list elements alphabetically or in ascending order.

The first parameter specifies the object to be sorted.

The second optional parameter of the method can be reverse, which specifies the sorting direction. By default, it has the value False.

In the third optional parameter, you can specify a callback function with sorting criteria.

Syntax

sorted(object, [list reversal mode], [function for sorting])

Example

Let's sort our list in reverse order:

lst1 = ['c', 'a', 'd', 'b', 'f', 'e'] lst2 = sorted(lst1, reverse=True) print(lst2)

Result of code execution:

['f', 'e', 'd', 'c', 'b', 'a']

Example

Now let's sort the list of numbers in reverse order:

lst1 = [10, 8, 2, 6, 14] lst2 = sorted(lst1, reverse=True) print(lst2)

Result of code execution:

[14, 10, 8, 6, 2]

Example

Let's sort our list of letters without specifying a parameter in the sorted function:

lst1 = ['c', 'a', 'd', 'b', 'f', 'e'] lst2 = sorted(lst1) print(lst2)

Result of code execution:

['a', 'b', 'c', 'd', 'e', 'f']

Example

Now let's sort the list of numbers:

lst1 = [10, 8, 2, 6, 14] lst2 = sorted(lst1) print(lst2)

Result of code execution:

[2, 6, 8, 10, 14]

Example

Let's sort the set:

st = {'a', 'b', 'c', 'd', 'e', 'f'} lst = sorted(st) print(lst)

Result of code execution:

['a', 'b', 'c', 'd', 'e', 'f']

Example

Let's sort the tuple:

tpl = ('a', 'b', 'c', 'd', 'e', 'f') lst = sorted(tpl) print(lst)

Result of code execution:

['a', 'b', 'c', 'd', 'e', 'f']

Example

Let's sort the dictionary:

dct = { '6': 'f', '2': 'b', '4': 'd', '3': 'c', '1': 'a', '5': 'e' } lst = sorted(dct) print(lst)

After executing the code, the function will return us a sorted list of dictionary keys:

['1', '2', '3', '4', '5', '6']

Example

You can also sort a string using the sorted function:

str = 'dacbfe' lst = sorted(str) print(lst)

But after execution we will also get back a sorted list:

['a', 'b', 'c', 'd', 'e', 'f']

See also

  • method sort,
    which sorts the elements of a list
  • function filter,
    which filters iterable objects
byenru