Info Node: (python2.1-lib.info)Mutable Sequence Types
(python2.1-lib.info)Mutable Sequence Types
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 (1)
`S[len(S):len(S)] =
[X]'
S.extend(X) same as (2)
`S[len(S):len(S)] = X'
S.count(X) return number of I's
for which `S[I] == X'
S.index(X) return smallest I such (3)
that `S[I] == X'
S.insert(I, X) same as `S[I:I] = [X]'
if `I >= 0'
S.pop([I]) same as `X = S[I]; del (4)
S[I]; return X'
S.remove(X) same as `del (3)
S[S.index(X)]'
S.reverse() reverses the items of S (5)
in place
S.sort([CMPFUNC]) sort the items of S in (5), (6)
place
{types}
Notes:
`(1)'
The C implementation of Python has historically accepted multiple
parameters and implicitly joined them into a tuple; this no longer
works in Python 2.0. Use of this misfeature has been deprecated
since Python 1.4.
`(2)'
Raises an exception when X is not a list object. The `extend()'
method is experimental and not supported by mutable sequence types
other than lists.
`(3)'
Raises `ValueError' when X is not found in S.
`(4)'
The `pop()' method is only supported by the list and array types.
The optional argument I defaults to `-1', so that by default the
last item is removed and returned.
`(5)'
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.
`(6)'
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 the methods `sort()' and `reverse()' than
to use the built-in function `sort()' with a comparison function
that reverses the ordering of the elements.