next up previous contents
Next: Tuple Objects Up: Lists, Tuples and Dictionaries Previous: The in operator   Contents

Functions and Methods for Lists

As mentioned previously the len function will return the number of elements in a list. When called with a single list argument, the min function returns the smallest element of a list, and the max function returns the largest. When you provide more than one argument to these functions, the return the smallest (min) or largest (max) element among the arguments passed to the function.

The functions mentioned above accept a list as an argument, and return the desired result. However, many list operations are performed through methods instead of functions. Unlike strings (Section 2.4.4), lists are mutable objects, so many methods which operate on lists will change the list - the return value from the method should not be assigned to any object.

To add a single element to a list, use the append method. Its single argument is the element to be appended.

>>> furniture = ['couch','chair','table']
>>> furniture.append('footstool')
>>> furniture
['couch', 'chair', 'table', 'footstool']
If the argument to the append method is a list, then a single (list) element will be appended to the list to which the method is applied; if you need to add several elements to the end of a list, there are two choices. You can use the concatenation operator (Section 4.3.1) or the extend method. The extend method takes a single argument, which must be a list, and adds the elements contained in the argument to the end of a list. Notice the difference between invoking the extend and append methods in the following example:
>>> a = [1,5,7,9]
>>> b = [10,20,30,40]
>>> a.extend(b)
>>> a
[1, 5, 7, 9, 10, 20, 30, 40]
>>> a = [1,5,7,9]
>>> a.append(b)
>>> a
[1, 5, 7, 9, [10, 20, 30, 40]]
(Since the extend method changes the object on which it operates, it was necessary to reinitialize a before invoking the append method. An alternative would have been to use the copy function (Section 8.9) to make a copy of a for the second method.) Note that with extend, the elements of b were added to a as individual elements; thus the length of a is the total of its old length and the length of b, but when using append, b is added to a as a single element; the length of a list is always increased by exactly one when append operates on it.

In many cases we want to create a new list incrementally, by adding one element to the list at a time. As a simple example, suppose we have a list of numbers and we want to create a second list containing only those numbers which are less than 0. If we try to append an element to a non-existent list, it raises a NameError exception:

>>> oldlist = [7, 9, -3, 5, -8, 19]
>>> for i in oldlist:
...     if i < 0 : newlist.append(i)
Traceback (innermost last):
  File "<stdin>", line 2, in ?
NameError: newlist
(Don't worry if you don't understand the details of the for and if statements; they will be covered in Sections 6.5 and 6.4, respectively.) The solution is to assign an empty list to newlist before we begin the loop. Such a list will have a length of zero, and no elements; the purpose of the assignment is simply to inform python that we will eventually refer to newlist as a list.
>>> oldlist = [7, 9, -3, 5, -8, 19]
>>> newlist = [ ]
>>> for i in oldlist:
...     if i < 0 : newlist.append(i)
>>> newlist
[-3, -8]

To add an item to a list at a location other than the end, the insert method can be used. This method takes two arguments; the first is the index at which the item is to be inserted, and the second is the item itself. Note that only one element can be inserted into a list using this method; if you need to insert multiple items, slicing (Section 4.2) can be used.

To remove an item from a list, based on its value, not its subscript, python provides the remove method. It accepts a single argument, the value to be removed. Note that remove only removes the first occurence of a value from a list.

The reverse and sort methods perform their operations on a list in place; in other words, when these methods are invoked on a list, the ordering of the elements in the list is changed, and the original ordering is lost. The methods do not return the reversed or sorted lists, so you should never set a list to the value returned by these methods! If you wish to retain the list with the elements in their original order, you should copy the list (using the copy module, not a regular assignment; see Section 6.1 and Section 8.9).

By default, the sort method sorts its numeric arguments in numerical order, and string arguments in alphabetical order Since a list can contain arbitrary objects, sort needs to be very flexible; it generally sorts scalar numeric values before scalar string values, and it sorts lists by first comparing their initial elements, and continuing through the available list elements until one list proves to be different than the other.

To sort in some other order than the method's default, a comparison function accepting exactly two arguments can be supplied as an argument to sort This function should be modeled on the built-in function cmp, which returns 1 if its first argument is greater than the second, 0 if the two arguments are equal, and -1 if the second argument is greater than the first. We'll look at function definitions in more detail later, but let's say we wish to sort strings, ignoring the case of the strings. The lower function in the string module can be used to return the lower case version of a string, and if we use that to compare pairs of values, the strings will be sorted without regard to case. We can write and use a function to do this comparison as follows:

>>> def nocase(a,b):
...     return cmp(a.lower(),b.lower())
>>> names = ['fred','judy','Chris','Sam','alex','Heather']
>>> copynames = names[:]
>>> names.sort()
>>> names
['Chris', 'Heather', 'Sam', 'alex', 'fred', 'judy']
>>> names = copynames[:]
>>> names.sort(nocase)
>>> names
['alex', 'Chris', 'fred', 'Heather', 'judy', 'Sam']

The count method counts how many times a particular value appears in a list. It accepts a single argument which represents the value you're looking for, and returns the number of times that the value appears in the list.

The index method accepts a single argument, and, if that argument is found in the list, it returns the index (subscript) of its first occurence. If the value is not in the list, a ValueError exception is raised.

The following example demonstrates the use of count and index.

>>> food = ['spam','spam','spam','sausage','spam']
>>> food.count('spam')
>>> food.index('spam')
Even though ``spam'' appears four times in the food list, the index method always returns the index of the first occurence of the value only. If the index method fails to find the requested element, a ValueError exception is raised.

Related Modules : copy, array, struct

Related Exceptions : IndexError, ValueError

next up previous contents
Next: Tuple Objects Up: Lists, Tuples and Dictionaries Previous: The in operator   Contents
Phil Spector 2003-11-12