List objects support additional operations that allow in-place modification of the object. Other mutable sequence types (when added to the language) should also support these operations. Strings and tuples are immutable sequence types: 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[i:j:k] = t |
the elements of s[i:j:k] are replaced by those of t |
(1) |
del s[i:j:k] |
removes the elements of s[i:j:k] from the list |
|
s.append(x) |
same as s[len(s):len(s)] = [x] |
(2) |
s.extend(x) |
same as s[len(s):len(s)] = x |
(3) |
s.count(x) |
return number of i's for which s[i] == x |
|
s.index(x[, i[, j]]) |
return smallest k such that s[k] == x and
i <= k < j |
(4) |
s.insert(i, x) |
same as s[i:i] = [x] |
(5) |
s.pop([i]) |
same as x = s[i]; del s[i]; return x |
(6) |
s.remove(x) |
same as del s[s.index(x)] |
(4) |
s.reverse() |
reverses the items of s in place | (7) |
s.sort([cmpfunc=None]) |
sort the items of s in place | (7), (8), (9), (10) |
-1
,
so that by default the last item is removed and returned.
None
as an equivalent to omitting
cmpfunc was added.
As an example of using the cmpfunc argument to the sort() method, consider sorting a list of sequences by the second element of that list:
def mycmp(a, b): return cmp(a[1], b[1]) mylist.sort(mycmp)
A more time-efficient approach for reasonably-sized data structures can often be used:
tmplist = [(x[1], x) for x in mylist] tmplist.sort() mylist = [x for (key, x) in tmplist]
See About this document... for information on suggesting changes.