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
sortandreversemethods.
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
sortmethod 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
reversemethod reverses the elements in a list.