liveBook · Manning

Sorting algorithm

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

Sorting is the operation of arranging collection elements according to an ordering criterion.

Sorting arranges collection elements according to an ordering criterion. Python provides both the list.sort() method, which changes a list in place and returns None, and the sorted() function, which returns a new list while preserving the original. section 3.3.7

Choose the operation according to how the surrounding program should handle its data:

  • Use list.sort() when modifying the existing list is appropriate; pass reverse=True for descending order. section 3.3.7
  • Use sorted(items) when the original order must remain available or when sorting another iterable, such as a set. section 3.3.7 section 20.3.5
  • Expect numeric values to sort numerically, while mixing strings and numbers raises a TypeError. section 3.3.7

Sorting picnic arguments

A command-line program can sort its collected items only when requested: if args.sorted: items.sort(). Running ./picnic.py --sorted salad soda cupcakes produces “You are bringing cupcakes, salad, and soda.” section 3.6.2 section 3.2

$ ./picnic.py --sorted salad soda cupcakes
You are bringing cupcakes, salad, and soda.

See the complete command-line result of sorting picnic items before formatting them. section 3.2

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

How deep it goes
Explains in-place and returned-list operations, reverse ordering, numeric behavior, and mixed-type errors, but not sorting algorithms internally.
Examples
Demonstrates sorted picnic output, REPL lists, descending order, numeric values, mixed-type failure, and sorted password words.
What it assumes
Assumes familiarity with Python lists and teaches sorting alongside list mutation, slicing, reversing, and formatted output.
What you can do after
Apply it via Python list.sort() or sorted() to order data while choosing whether to mutate or preserve the original.
How it connects
Connects sorting with lists, iterables, mutation, iterators, command-line arguments, and reproducible testing.

Also explained in

Compare how 18 books explain sorting algorithm →

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.