2.1.5.2 Mutable Sequence Types

List objects support additional operations that allow in-place modification of the object. These operations would be supported by other mutable sequence types (when added to the language) as well. Strings and tuples are immutable sequence types and such objects cannot be modified once created. The following operations are defined on mutable sequence types (where x is an arbitrary object):

Operation Result Notes
s[i] = x item i of s is replaced by x
s[i:j] = t slice of s from i to j is replaced by t
del s[i:j] same as s[i:j] = []
s.append(x) same as s[len(s):len(s)] = [x]
s.extend(x) same as s[len(s):len(s)] = x (5)
s.count(x) return number of i's for which s[i] == x
s.index(x) return smallest i such that s[i] == x (1)
s.insert(i, x) same as s[i:i] = [x] if i >= 0
s.pop([i]) same as x = s[i]; del s[i]; return x (4)
s.remove(x) same as del s[s.index(x)] (1)
s.reverse() reverses the items of s in place (3)
s.sort([cmpfunc]) sort the items of s in place (2), (3)
20 21 22 23 24 25 26 27 28 Notes:

(1)
Raises an exception when x is not found in s.
(2)
The sort() method takes an optional argument specifying a comparison function of two arguments (list items) which should return -1, 0 or 1 depending on whether the first argument is considered smaller than, equal to, or larger than the second argument. Note that this slows the sorting process down considerably; e.g. to sort a list in reverse order it is much faster to use calls to sort() and reverse() than to use sort() with a comparison function that reverses the ordering of the elements.

(3)
The sort() and reverse() methods modify the list in place for economy of space when sorting or reversing a large list. They don't return the sorted or reversed list to remind you of this side effect.

(4)
The pop() method is experimental and not supported by other mutable sequence types than lists. The optional argument i defaults to -1, so that by default the last item is removed and returned.

(5)
Raises an exception when x is not a list object. The extend() method is experimental and not supported by mutable types other than lists.