Section 6.14. List Type Built-in Methods


6.14. 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(). 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.

We can use dir() on a list object to get its attributes including its methods:

>>> dir(list)    # or dir([]) ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__delslice__', '__doc__', '__eq__', '__ge__', '__getattribute__', '__getitem__', '__getslice__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__setslice__', '__str__', 'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']


Table 6.11 shows all the methods currently available for lists. Some examples of using various list methods are shown later.

Table 6.11. List Type Built-in Methods

List Method

Operation

list.append(obj)

Adds obj to the end of list

list.count(obj)

Returns count of how many times obj occurs in list

list.extend(seq)[a]

Appends contents of seq to list

list.index(obj, i=0, j=len(list))

Returns lowest index k where list[k]==obj and i<= k<j; otherwise ValueError raised

list.insert(index, obj)

Inserts obj into list at offset index

list.pop(index=-1)[a]

Removes and returns obj at given or last index from list

list.remove(obj)

Removes object obj from list

list.reverse()

Reverses objects of list in place

list.sort(func=None, key=None, reverse=False)[b]

Sorts list members with optional comparison function; key is a callback when extracting elements for sorting, and if reverse flag is true, then list is sorted in reverse order


[a] New in Python 1.5.2.

[b] Support for key and reverse added in Python 2.4.

>>> 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 preceding 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 and 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 False >>> 'compact disc' in music_media True >>> 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', 45]


Core Note: Mutable object methods that alter the object have no return value!

One very obvious place where new Python programmers get caught is when using methods that you think should return a value. The most obvious one is sort():

>>> music_media.sort()        # where is the output?!? >>>


The caveat about mutable object methods like sort(), extend(), and reverse() is that these will perform their operation on a list in place, meaning that the contents of the existing list will be changed, but return None! Yes, it does fly in the face of string methods that do return values:

>>> 'leanna, silly girl!'.upper() 'LEANNA, SILLY GIRL!'


Recall that strings are immutablemethods of immutable objects cannot modify them, so they do have to return a new object. If returning an object is a necessity for you, then we recommend that you look at the reversed() and sorted() built-in functions introduced in Python 2.4.

These work just like the list methods only they can be used in expressions because they do return objects. However, obviously the original list object is left as is, and you are getting a new object back.


Going back to the sort() method, the default sorting algorithm employed by the sort() method is a derivative of MergeSort (modestly named "timsort"), which is O(lg(n!)). We defer all other explanation to the build files where you can get all the detailssource code: Objects/listobject.c and algorithm description: Objects/listsort.txt.

The 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 iterable, starting with 2.2. Prior to that, it had to be a sequence object, and prior to 1.6, it had to be a list. With an iterable (instead of a sequence), you can do more interesting things like:

>>> motd = [] >>> motd.append('MSG OF THE DAY') >>> f = open('/etc/motd', 'r') >>> motd.extend(f) >>> f.close() >>> motd ['MSG OF THE DAY', 'Welcome to Darwin!\n']


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



Core Python Programming
Core Python Programming (2nd Edition)
ISBN: 0132269937
EAN: 2147483647
Year: 2004
Pages: 334
Authors: Wesley J Chun

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net