June 2017
Beginner
352 pages
8h 39m
English
Before we move on from lists, let's look at two operations which rearrange the elements in place: Reversing and sorting.
A list can be reversed in place simply by calling it's reverse() method:
>>> g = [1, 11, 21, 1211, 112111]>>> g.reverse()>>> g[112111, 1211, 21, 11, 1]
A list can be sorted in place, using the sort() method:
>>> d = [5, 17, 41, 29, 71, 149, 3299, 7, 13, 67]>>> d.sort()>>> d[5, 7, 13, 17, 29, 41, 67, 71, 149, 3299]
The sort() method accepts two optional arguments, key and reverse. The latter is self explanatory and when set to True gives a descending sort:
>>> d.sort(reverse=True)>>> d[3299, 149, 71, 67, 41, 29, 17, 13, 7, 5]
The key parameter is more interesting. It accepts any callable object ...
Read now
Unlock full access