6.13. List Type Built-in Methods

Lists in Python have methods. We will go over methods more formally in an introduction to object-oriented programming in Chapter 13, but for now, think of methods as functions or procedures that apply only to specific objects. So the methods described in this section behave just like built-in functions except that they operate only on lists. Since these functions involve the mutability (or updating) of lists, none of them is applicable for tuples.

You may recall our earlier discussion of accessing object attributes using the dotted attribute notation: object.attribute. List methods are no different, using list.method([arguments]). We use the dotted notation to access the attribute (here it is a function), then use the function operators ( ( ) ) in a functional notation to invoke the methods.

Types that have methods generally have an attribute called object.__methods__ which name all the methods that are supported by that type. In our case for lists, list.__methods__ serves this purpose:

>>> [].__methods__
['append', 'count', 'extend', 'index', 'insert', 'pop',
'remove', 'reverse', 'sort']

Table6.10 shows all the current methods currently available for lists. Of these methods, extend() and pop() made their debut in Python 1.5.2. Some examples of using various list methods are shown below.

Table 6.10. List Type Built-in Methods
List MethodOperation
list.append(obj)appends object obj to list
list.count(obj)returns count of how many times obj occurs in list
list.extend(seq)[a]appends the contents of seq to list
list.index(obj)returns the lowest index in list that obj appears
list.insert(index, obj)inserts object obj into list at offset index
list.pop(obj=list[-1])[a]removes and returns last object or obj from list
list.remove(obj)removes object obj from list
list.reverse()reverses objects of list in place
list.sort([func])sorts objects of list, use compare func if given

[a] new as of Python 1.5.2

>>> music_media = [45]
>>> music_media
[45]
>>>
>>> music_media.insert(0, 'compact disc')
>>> music_media
['compact disc', 45]
>>>
>>> music_media.append('long playing record')
>>> music_media
['compact disc', 45, 'long playing record']
>>>
>>> music_media.insert(2, '8-track tape')
>>> music_media
['compact disc', 45, '8-track tape', 'long playing record']

In the preceeding example, we initiated a list with a single element, then checked the list as we either inserted elements within the list, or appended new items at the end. Let's now determine if elements are in a list as well as how to find out the location of where items are in a list. We do this by using the in operator and index() method.

>>> 'cassette' in music_media
0
>>> 'compact disc' in music_media
1
>>> music_media.index(45)
1
>>> music_media.index('8-track tape')
2
>>> music_media.index('cassette')
Traceback (innermost last):
 File "<interactive input>", line 0, in ?
ValueError: list.index(x): x not in list

Oops! What happened in that last example? Well, it looks like using index() to check if items are in a list is not a good idea, because we get an error. It would be safer to check using the membership operator in (or not in) first, and then using index() to find the element's location. We can put the last few calls to index() in a single for loop like this:

						for eachMediaType in (45, '8-track tape', 'cassette'):
    if eachMediaType in music_media:
        print music_media.index(eachMediaType)

This solution helps us avoid the error we encountered above because index() is not called unless the object was found in the list. We will find out later how we can take charge if the error occurs, instead of bombing out as we did above.

We will now test drive sort() and reverse(), methods that will sort and reverse the elements of a list, respectively.

>>> music_media
['compact disc', 45, '8-track tape', 'long playing record']
>>> music_media.sort()
>>> music_media
[45, '8-track tape', 'compact disc', 'long playing record']
>>> music_media.reverse()
>>> music_media
['long playing record', 'compact disc', '8-track tape', 4

One caveat about the sort() and reverse() methods is that these will perform their operation on a list in place, meaning that the contents of the existing list will be changed. There is no return value from either of these methods.

Oh, and if you are an algorithm connoisseur, the default sorting algorithm employed by the sort() method is a randomized version of QuickSort. We defer all other explanation to the portion of the source code where you can find out more information on the sorting algorithm (Objects/listobject.c).

The new extend() method will take the contents of one list and append its elements to another list:

>>> new_media = ['24/96 digital audio disc', 'DVD Audio
disc', 'Super Audio CD']
>>> music_media.extend(new_media)
>>> music_media
['long playing record', 'compact disc', '8-track tape',
45, '24/96 digital audio disc', 'DVD Audio disc', 'Super
Audio CD']

The argument to extend() can be any sequence object starting in Python 1.6—the sequence is converted to a list by performing the equivalent to list() and then its contents appended to the original list. In 1.5.2, the argument was required to be a list.

pop() will either return the last or requested item from a list and return it to the caller. We will see the new pop() method in Section 6.14.1 as well as in the Exercises.

..................Content has been hidden....................

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