liveBook · Manning

Sorting algorithm

As explained in Python How-To

Sorting is the process of arranging elements into an order determined by a comparison or key function.

Need to show tasks by urgency rather than creation order? Sorting rearranges their list into the order you choose. Python’s list.sort() changes the original list in place and returns None; by default, it sorts in ascending order. Use reverse=True for descending order. section 3.2 section 3.2.1

For numbers or strings, the default comparisons may be enough. Dictionaries cannot be compared that way, so give sort() a key function. It receives one item and returns the value used to place that item in order; the list still contains the original items. section 3.2 section 3.2.2 section 3.2.3

Put the most urgent task first

tasks = [{'title': 'Laundry', 'urgency': 3}, {'title': 'Homework', 'urgency': 5}, {'title': 'Museum', 'urgency': 2}] def urgency(task): return task['urgency'] tasks.sort(key=urgency, reverse=True) print([task['title'] for task in tasks]) # ['Homework', 'Laundry', 'Museum'] The key selects each task’s urgency; reverse=True puts the highest value first. section 3.2 section 3.2.3

Choose the sorting operation that fits the job:

  • Use list.sort() when changing the existing list is intended. Do not chain another method onto its result: that result is None. section 3.2.1 section 6.2.1
  • Use sorted() when you need a new sorted list, including when the input is another iterable such as a tuple, set, or dictionary. section 3.2.4 section 5.3.6
  • Use a one-argument key function for a custom order. A short lambda can express a small key operation; len can serve as a key when length determines rank. section 3.2.3 section 3.2.5

A key can also make otherwise incompatible items comparable: key=str sorts mixed items by their string forms while retaining the original objects. Choose that rule only when string order is the order you actually want. section 3.2.1 section 3.2.2

How Python How-To covers it

How deep it goes
Explains default and key-based sorting through worked Python examples; does not develop a sorting algorithm’s internals.
Examples
Uses number and name lists, mixed-type comparison errors, urgency-ranked task dictionaries, and a description-length challenge.
What it assumes
Assumes familiarity with lists, dictionaries, and basic functions; defers lambda-function instruction.
What you can do after
Apply it via list.sort() or sorted() to order data with default comparisons or a custom key.
How it connects
Connects sorting to mutable lists, iterables, key functions, lambda functions, and function return values.

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 Python How-To. The section links point to the parts of the book it draws on.