In Python, the sorted() function is used to sort a sequence. It does not modify the original sequence but returns a new sorted sequence, and custom sorting rules can be applied.

Function Syntax

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

Parameters:

  • iterable: The sequence to be sorted. It can be a list, tuple, set, or any other iterable object.
  • key: Optional. Specifies a function that extracts a comparison key from each element. If not specified, the elements themselves are used for comparison.
  • reverse: Optional. Specifies the sorting order. True for descending order, False for ascending order. Default is False.

The sorted() function does not modify the original sequence; instead, it returns a new sorted list.

Examples of the sorted() Function

Here are some usage examples:

# Ascending order sort
lst = [3, 1, 4, 1, 5, 9]
sorted_lst = sorted(lst)
print(sorted_lst) # [1, 1, 3, 4, 5, 9]
# Does not change the original sequence
print(lst)        # [3, 1, 4, 1, 5, 9]

# Descending order sort
sorted_lst = sorted(lst, reverse=True)
print(sorted_lst) # [9, 5, 4, 3, 1, 1]

# Specifying a sort key
sorted_lst = sorted(lst, key=lambda x: x % 3)
print(sorted_lst) # [3, 9, 1, 4, 1, 5]

d = {'a': 3, 'b': 1, 'c': 4, 'd': 1, 'e': 5}
sorted_keys = sorted(d, key=lambda k: d[k])
print(sorted_keys)  # ['b', 'd', 'a', 'c', 'e']