Introduction to Python ProgrammingXYZ Homework Edition

⇩ Download ▾

9.2 Sorting and reversing lists

Learning objectives

By the end of this section you should be able to

  • Understand the concept of sorting.
  • Use built-in sort and reverse methods.

Sorting

Ordering elements in a sequence is often useful. Sorting is the task of arranging elements in a sequence in ascending or descending order.

Sorting can work on numerical or non-numerical data. When ordering text, dictionary order is used. Ex: "bat" comes before "cat" because "b" comes before "c".

Using sort and reverse

Python provides methods for arranging elements in a list.

  • The sort method arranges the elements of a list in ascending order. For strings, ASCII values are used and uppercase characters come before lowercase characters, leading to unexpected results. Ex: "A" is ordered before "a" in ascending order but so is "G"; thus, "Gail" comes before "apple".
  • The reverse method reverses the elements in a list.

Adapted from Introduction to Python Programming by OpenStax (openstax.org), licensed under CC BY-NC-SA 4.0. Changes were made. License: CC-BY-NC-SA-4.0.

These eBooks are a prerelease and are not yet certified conformant with WCAG 2.1 AA or ADA Title II. Every page is built against an automated accessibility gate, and the published editions will meet ADA Title II requirements when they release in late September 2026. If something is unusable, please tell us.