liveBook · Manning

Sorted

As explained in Tiny Python Projects: Learn coding and testing with puzzles and games

sorted is a Python built-in function that returns a new list containing the sorted elements of an iterable without modifying the original.

sorted() accepts an iterable and returns a new list in sorted order, leaving the original collection unchanged. It is useful when the ordered result matters but the input must remain available in its original order. section 3.3.7

Keep these behaviors distinct:

  • sorted(items) produces a new list; items.sort() sorts the existing list in place and returns None. section 3.3.7
  • sorted([4, 2, 10, 3, 1]) returns [1, 2, 3, 4, 10], while mixed strings and numbers raise a TypeError. section 3.3.7
  • Sorting a set creates a list with a consistent order, which supports reproducible calls to random.sample(). section 20.1.6

Preserve the input while sorting

>>> items = ['soda', 'sammiches', 'chips', 'ice cream'] >>> sorted_items = sorted(items) >>> sorted_items ['chips', 'ice cream', 'sammiches', 'soda'] >>> items ['soda', 'sammiches', 'chips', 'ice cream'] A command-line program can apply this behavior when the user supplies a --sorted Boolean flag. A password generator can similarly use words = sorted(words) before random.sample(words, args.num_words). section 3.3.7 section 3.4.1 section 20.1.6

>>> items = ['soda', 'sammiches', 'chips', 'ice cream']
>>> sorted(items)
['chips', 'ice cream', 'sammiches', 'soda']

Inspect the REPL comparison between sorted(items) and the unchanged original list. section 3.3.7

How Tiny Python Projects: Learn coding and testing with puzzles and games covers it

How deep it goes
Distinguishes returned lists from in-place mutation, demonstrates numeric and mixed-type behavior, and stops short of advanced sorting arguments.
Examples
Demonstrates picnic-item sorting, REPL list comparisons, numeric ordering, password-word preparation, and test-driven command-line work.
What it assumes
Assumes familiarity with Python lists and function calls while reinforcing mutation, return values, sets, flags, and basic testing.
What you can do after
Apply sorted() to preserve input data, order command-line items, and make set-based random sampling deterministic for tests.
How it connects
Links sorted() with iterables, lists, sets, list.sort(), reversed(), random.sample(), and reproducible testing.

Also explained in

Compare how 5 books explain sorted →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Tiny Python Projects: Learn coding and testing with puzzles and games. The section links point to the parts of the book it draws on.