Learn how to use the function, "sorted", to sort iterables with the help of the examples provided.

sorted function

We met the sorted function briefly in the Functions as Objects chapter. Here it is again in a bit more detail.

sorted isn’t quite like the other transforming functions. It will work on any iterable, but it doesn’t produce an iterator as output; instead, it always creates a list. This doesn’t usually cause any problems, but it is worth knowing. It is interesting to compare sorted and reversed. They are both restricted but in different ways:

  • reversed requires a sequence as input but creates a lazy iterator as output. This is because the first thing you need to output when you reverse a series is the last element. You can’t reverse a series unless you have random access to its elements, so a sequence is required as input.
  • sorted can accept a lazy iterator as input but creates a list as output. Python uses a sorting algorithm, called Timsort, that is derived from a hybrid of merge sort and insertion sort. The algorithm can accept data, element by element, but requires random access to the output list to place the elements in the correct final position.

Get hands-on with 1200+ tech skills courses.