Rearranging list elements

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 which is then used to extract a key from each item. The items will then be sorted according to the relative ordering of these keys.
There are several types of callable objects in Python, although the only one we have encountered so far is the humble function. For example, the len() function is a callable object which is used to determine the length of a collection, such as a string.

Consider the following list of words:

>>> h = 'not perplexing do handwriting family where I illegibly know doctors'.split()
>>> h
['not', 'perplexing', 'do', 'handwriting', 'family', 'where', 'I', 'illegibly', 'know', 'doctors']
>>> h.sort(key=len)
>>> h
['I', 'do', 'not', 'know', 'where', 'family', 'doctors', 'illegibly', 'perplexing', 'handwriting']
>>> ' '.join(h)
'I do not know where family doctors illegibly perplexing handwriting'
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset