Learning objectives
By the end of this section you should be able to
- Understand the concept of sorting.
- Use built-in
sort()
andreverse()
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".
Concepts in Practice
Sorting
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.
Example 9.2
Sorting and reversing lists
# Setup a list of numbers
num_list = [38, 92, 23, 16]
print(num_list)
# Sort the list
num_list.sort()
print(num_list)
# Setup a list of words
dance_list = ["Stepping", "Ballet", "Salsa", "Kathak", "Hopak", "Flamenco", "Dabke"]
# Reverse the list
dance_list.reverse()
print(dance_list)
# Sort the list
dance_list.sort()
print(dance_list)
The above code's output is:
[38, 92, 23, 16] [16, 23, 38, 92] ["Dabke", "Flamenco", "Hopak", "Kathak", "Salsa", "Ballet", "Stepping"] ["Ballet", "Dabke", "Flamenco", "Hopak", "Kathak", "Salsa", "Stepping"]
Concepts in Practice
sort() and reverse() methods
Use the following list for the questions below.
board_games = ["go", "chess", "scrabble", "checkers"]
Try It
Sorting and reversing
Complete the program below to arrange and print the numbers in ascending and descending order.