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
x in smembership 
x not in s
for a in siteration 
min(s)return smallest element 
max(s)return greatest element 
s[i] = xindex assignment  
s[i:k] = tslice assignment  
del s[i]deletion  

[a] shallow copy (see Section 10.2)

Table 9.2. List methods

list(s)converts any sequence object to a list
s.append(x)append a new element
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.sort([cmp])[b]sort according to the cmp function

[a] equal to the + operator but inplace

[b] in place operation


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
>>> l1 + l2
['EcoRI', 'BamHI', 'HindIII']
>>> l1 
['EcoRI', 'BamHI']
>>> l2
>>> l1.extend(l2)
>>> l1
['EcoRI', 'BamHI', 'HindIII']
>>> l2