sorted() belong to python Built in sorting function , It is used to arrange each element of an iteratable object in ascending order ( default ) And return the results as a list .

Optional parameters key Used for user-defined sorting rules ; Optional parameters reverse Choose ascending or descending order ( default False, Indicates ascending order ).

be careful : The built-in method and the method properties of the list object sort() It is very similar in function and usage .

>>> help(sorted)

Help on built-in function sorted in module builtins:

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

Return a new list containing all items from the iterable in ascending order.

A custom key function can be supplied to customize the sort order, and the

reverse flag can be set to request the result in descending order.

# Examples 1:

>>> nums = [4,3,1,6,9,12]

>>> sorted(nums)

[1, 3, 4, 6, 9, 12]

# example 2: Descending order

>>> s = 'hello world'

>>> sorted(s, reverse=True)

['w', 'r', 'o', 'o', 'l', 'l', 'l', 'h', 'e', 'd', ' ']

# example 3: appoint key

>>> users = [{'name':'jack', 'age':26}, {'name':'cindy', 'age':19}]

>>> sorted(users, key=lambda x:x['age'])

[{'name': 'cindy', 'age': 19}, {'name': 'jack', 'age': 26}]

Technology