Python built-in Method - sorted()

The sorted() function is a built-in Python method that is used to sort a sequence or iterable object (such as a list, tuple, or string) in ascending or descending order. The sorted() function returns a new sorted list, leaving the original sequence unchanged.

The syntax for the sorted() function is as follows:

r‮efe‬r to:theitroad.com
sorted(iterable, *, key=None, reverse=False)
  • iterable: The sequence or iterable object to be sorted.
  • key (optional): A function that returns a value to be used as the sort key. If this parameter is not specified, the default behavior is to compare the elements directly.
  • reverse (optional): A boolean value indicating whether the sequence should be sorted in descending order. The default is False (ascending order).

Here are some examples of how the sorted() function can be used:

>>> lst = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
>>> sorted_lst = sorted(lst)
>>> print(sorted_lst)
[1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]

In this example, we create a list lst with eleven elements. We then use the sorted() function to create a new list sorted_lst that contains the elements of lst in ascending order.

>>> lst = ['apple', 'banana', 'cherry', 'date', 'elderberry']
>>> sorted_lst = sorted(lst, key=len)
>>> print(sorted_lst)
['date', 'apple', 'banana', 'cherry', 'elderberry']

In this example, we create a list lst with five elements. We then use the sorted() function with the key parameter set to a function that returns the length of a string to create a new list sorted_lst that contains the elements of lst sorted by length.

>>> dct = {'apple': 3, 'banana': 2, 'cherry': 5, 'date': 3, 'elderberry': 10}
>>> sorted_keys = sorted(dct.keys())
>>> print(sorted_keys)
['apple', 'banana', 'cherry', 'date', 'elderberry']

In this example, we create a dictionary dct with five key-value pairs. We then use the sorted() function to create a new list sorted_keys that contains the keys of dct in ascending order.

The sorted() function is a useful built-in method in Python that provides a convenient way to sort a sequence or iterable object in ascending or descending order. The function can be used with a variety of built-in data types and can be customized with the key parameter to sort based on a custom function.