9.2. Methods, Operators and Functions on Lists

Table 9.1 remembers the action of builtin functions and operators on list objects and Table 9.2 summarizes all methods of list objects.

Table 9.1. Sequence types: Operators and Functions

Operator/FunctionActionAction on Numbers
[ ... ], ( ... ), " ... "creation 
s + tconcatenationaddition
s * nrepetition [a]multiplication
s[i]indication 
s[i:k]slice 
x in smembership 
x not in s
for a in siteration 
len(s)length 
min(s)return smallest element 
max(s)return greatest element 
s[i] = xindex assignment  
s[i:k] = tslice assignment  
del s[i]deletion  
Important

[a] shallow copy (see Section 10.2)

Table 9.2. List methods

MethodOperation
list(s)converts any sequence object to a list
s.append(x)append a new element
s.extend(t)concatenation[a]
s.count(x)count occurrences of x
s.index(x)find smallest position where x occurs in s
s.insert(i,x)insert x at position i
s.pop([i])removes i-th element and return it
s.remove(x)remove element
s.reverse()[b]reverse
s.sort([cmp])[b]sort according to the cmp function

[a] equal to the + operator but inplace

[b] in place operation

Important

It is important to know whether a function or method, that is applied to a mutable objects, modifies this object internally or whether it returns a new object containing these modifications. Look at the following example that shows two possibilities to concatenate lists. The + operator creates a new list whereas the method extend adds one list to the other:

>>> l1 = [ 'EcoRI', 'BamHI' ]
>>> l2 = [ 'HindIII' ]
>>> l1
['EcoRI', 'BamHI']
>>> l2
['HindIII']
>>> l1 + l2
['EcoRI', 'BamHI', 'HindIII']
>>> l1 
['EcoRI', 'BamHI']
>>> l2
['HindIII']
>>> l1.extend(l2)
>>> l1
['EcoRI', 'BamHI', 'HindIII']
>>> l2
['HindIII']