Next / Previous / Contents / TCC Help System / NM Tech homepage

4.4. List methods

We have already seen how all string values have methods. For example, if variable p contains the string "Path", the expression p.upper() returns a new string with all lowercase characters uppercased:

>>> p = "Path"
>>> p.upper()
'PATH'

Similarly, all list instances support several useful methods. For example, for any list instance L, the .append(v) method appends a new value v to that list.

>>> menu1 = ['kale', 'tofu']
>>> menu1
['kale', 'tofu']
>>> menu1.append ( 'sardines' )
>>> menu1
['kale', 'tofu', 'sardines']
>>> 

To insert a single new value V into a list L at an arbitrary position P, use this method:

L.insert(P, V)

To continue the example above:

>>> menu1
['kale', 'tofu', 'sardines']
>>> menu1.insert(0, 'beans')
>>> menu1
['beans', 'kale', 'tofu', 'sardines']
>>> menu1[3]
'sardines'
>>> menu1.insert(3, 'trifle')
>>> menu1
['beans', 'kale', 'tofu', 'trifle', 'sardines']

To find the position of a value V in a list L, use this method:

L.index(V)

This method returns the position of the first element of L that equals V. , or -1 i If no elements of L are equal, Python raises a ValueError exception.

>>> menu1
['beans', 'kale', 'tofu', 'trifle', 'sardines']
>>> menu1.index("kale")
1
>>> menu1.index("spam")
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
ValueError: list.index(x): x not in list

The method L.count(V) method returns the number of elements of L that are equal to V.

>>> menu1[2:2] = ['spam'] * 3
>>> menu1
['beans', 'kale', 'spam', 'spam', 'spam', 'tofu', 'trifle', 'sardines']
>>> menu1.count('gravy')
0
>>> menu1.count('spam')
3

The method L.remove(V) removes the first element of L that equals V, if there is one. If no elements equal V, the method raises a ValueError exception.

>>> menu1
['beans', 'kale', 'spam', 'spam', 'spam', 'tofu', 'trifle', 'sardines']
>>> menu1.remove('spam')
>>> menu1
['beans', 'kale', 'spam', 'spam', 'tofu', 'trifle', 'sardines']
>>> menu1.remove('spam')
>>> menu1
['beans', 'kale', 'spam', 'tofu', 'trifle', 'sardines']
>>> menu1.remove('gravy')
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
ValueError: list.remove(x): x not in list

The L.sort() method sorts the elements of a list into ascending order.

>>> menu1
['beans', 'kale', 'spam', 'tofu', 'trifle', 'sardines']
>>> menu1.sort()
>>> menu1
['tofu', 'beans', 'kale', 'sardines', 'spam', 'trifle']

Note that the .sort() method itself does not return a value; it sorts the values of the list in place. A similar method is .reverse(), which reverses the elements in place:

>>> menu1
['tofu', 'beans', 'kale', 'sardines', 'spam', 'trifle']
>>> menu1.reverse()
>>> menu1
['trifle', 'spam', 'sardines', 'kale', 'beans', 'tofu']