Operations on mutable sequences type list

Operations on mutable sequences




s[i] =x

item i of s is replaced by x

s[i:j [:step]] = t

slice of s from i to j is replaced by t

del s[i:j[:step]]

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



returns number of i's for which s[i] == x

s.index(x[, start[, stop]])

returns smallest i such that s[i] = =x. start and stop limit search to only part of the list.


s.insert(i, x)

same as s[i:i] = [x] if i>= 0. i = = -1 inserts before the last element.


same as del s[s.index(x)]



same as x = s[i]; del s[i]; return x



reverses the items of s in place


s.sort([cmp ]) s.sort([cmp=cmpFct] [, key= keyGetter] [, reverse=bool])

sorts the items of s in place

• (1) Raises a ValueError exception when x is not found in s (i.e. out of range).

• (2) The sort() method takes an optional argument cmp specifying a comparison function takings 2 list items and returning -1, 0, or 1 depending on whether the 1st argument is considered smaller than, equal to, or larger than the 2nd argument. Note that this slows the sorting process down considerably. Since 2.4, the cmp argument may be specified as a keyword, and 2 optional keywords args are added: key is a fct that takes a list item and returns the key to use in the comparison (faster than cmp); reverse: If True, reverse the sense of the comparison used.

Since Python 2.3, the sort is guaranteed "stable". This means that two entries with equal keys will be returned in the same order as they were input. For example, you can sort a list of people by name, and then sort the list by age, resulting in a list sorted by age where people with the same age are in name-sorted order.

• (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 not supported by mutable sequence types other than lists. The optional argument i defaults to -1, so that by default the last item is removed and returned.

• (5) Raises a TypeError when x is not a list object.

Was this article helpful?

0 0

Post a comment