liveBook · Manning

Sorted

As explained in The Quick Python Book, Fourth Edition

sorted is a Python built-in function that returns a new list containing the items of an iterable in sorted order.

sorted() is a Python built-in function that accepts any iterable and returns a new list containing its items in sorted order. Unlike list.sort(), it leaves the original iterable unchanged. section 5.4.2 section 5.4

x = (4, 3, 1, 2)
y = sorted(x)
y
 
[1, 2, 3, 4] 
 
z = sorted(x, reverse=True)
z
 
[4, 3, 2, 1]

A tuple becomes a newly returned list; reverse=True changes the order without changing the input. section 5.4.2

Use sorted() when:

  • You need to preserve the original list or iterable. section 5.4
  • You need descending order with reverse=True. section 5.4.2
  • You need a custom ordering with a key function, such as str.lower or a slice-based lambda. section 21.4.2

Default sorting requires comparable item types. Lists of lists are compared element by element, beginning with the first element and continuing to later elements when needed. Mixed numbers and strings raise TypeError. section 5.4

Preserving data while finding a median

For temperatures, use sorted_temps = sorted(temperatures) before selecting or calculating the middle value. This preserves the input order, but a sorted copy uses additional memory; for very large lists, in-place sorting may be preferable when preservation is unnecessary. section 5.9.3

For data larger than available memory, an external utility such as the UNIX sort command may be more practical. Also keep key functions simple because sorting calls them repeatedly. section 21.4.2

How The Quick Python Book, Fourth Edition covers it

How deep it goes
Explains return behavior, ordering options, comparison rules, custom keys, and memory trade-offs without descending into sorting internals.
Examples
Uses tuples, text lines, nested lists, mixed types, case-insensitive keys, sliced keys, and temperature-median calculations.
What you can do after
Apply it via Python to create sorted copies, reverse results, customize comparisons, and choose between memory-preserving and in-place alternatives.
How it connects
Connects sorted() with list.sort(), iterable objects, key functions, reverse ordering, nested-list comparison, and external sorting utilities.

Also explained in

Compare how 5 books explain sorted →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Quick Python Book, Fourth Edition. The section links point to the parts of the book it draws on.