16.2 Optional reverse parameter
From Foundations of Python ProgrammingGNU FDL 1.3Original pagePython1 class period1 exercise1 graded test
16.2 Optional reverse parameter
Read first in the book: 16.1 Introduction: Sorting with Sort and Sorted.
The sorted function takes some optional parameters (see the Optional Parameters page). The first optional parameter is a key function, which will be described in the next section. The second optional parameter is a Boolean value which determines whether to sort the items in reverse order. By default, it is False, but if you set it to True, the list will be sorted in reverse order.
L2 = ["Cherry", "Apple", "Blueberry"]
print(sorted(L2, reverse=True))
Note
For most functions, it is possible to provide optional parameters without keywords, but the
sortedfunction prevents this, so you have to provide keywords for thereverseandkeyparameters. In this situation, it is more convenient to use the keyword mechanism anyway.
Check Your Understanding
Exercise 1
1. Sort the list, lst from largest to smallest. Save this new list to the variable lst_sorted.
Open the
01folder and editmain.py. Run Tests checks it.
For teachers
16.2 Optional reverse parameter
Students read Foundations of Python Programming's “Optional reverse parameter” in CS Room and work through its 1 Python coding exercise (1 graded).
- Time: 1 class period
- Tests: 1 in 1 graded exercise, set up for you when you import the lesson
Reading first
Exercises
| Folder | Grading | Tests |
|---|---|---|
01 | Autograded | 1 |