All list instances have methods for changing the values in the list. These methods work only on lists. They do not work on the other sequence types that are not mutable, that is, the values they contain may not be changed, added, or deleted.
For example, for any list instance , the L.append( method
appends a new value v) to that list.
v
>>> menu1 = ['kale', 'tofu'] >>> menu1 ['kale', 'tofu'] >>> menu1.append ( 'sardines' ) >>> menu1 ['kale', 'tofu', 'sardines'] >>>
To insert a single new value into a list V at an arbitrary position L, use this method:
P
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']
The method removes
the first element of L.remove(V) that equals L, if there is one. If no elements equal V, the method
raises a VValueError 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
method sorts the elements of a list into ascending order.
L.sort()
>>> menu1 ['beans', 'kale', 'spam', 'tofu', 'trifle', 'sardines'] >>> menu1.sort() >>> menu1 ['beans', 'kale', 'sardines', 'spam', 'tofu', '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 ['beans', 'kale', 'sardines', 'spam', 'tofu', 'trifle'] >>> menu1.reverse() >>> menu1 ['trifle', 'tofu', 'spam', 'sardines', 'kale', 'beans']