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

Returns a new sorted list from the elements of the iterable.

Parameters

  • iterable: An object that supports iteration, whose elements need ordering.
  • key=None: A function that takes an element as an argument to obtain a value for comparison with others. Defaults to None, meaning elements are compared directly. For example: key=str.lower.
  • reverse=False: A flag indicating whether to sort in reverse order.

Return Value

The sorted() function returns a sorted list.

Examples

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

# Sort dictionary elements by keys.
sorted(my_dict.items(), key=lambda item: item[0])  
# [('a', 3), ('b', 2), ('c', 1)]

# Sort dictionary elements by values.
sorted(my_dict.items(), key=lambda item: item[1])  
# [('c', 1), ('b', 2), ('a', 3)]

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

# Sort by values and keys.
sorted(my_dict.items(), key=lambda item: (item[1], item[0]))
# [('c', 1), ('b', 2), ('0', 3), ('a', 3)]

# Sort by values in descending order and keys.
sorted(my_dict.items(), key=lambda item: (-item[1], item[0]))
# [('0', 3), ('a', 3), ('b', 2), ('c', 1)]

Sorting with this function is stable, meaning the order of equal elements remains unchanged. This is useful when sorting in multiple passes, such as by department and salary level.