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/Function | Action | Action on Numbers | ||||
|---|---|---|---|---|---|---|
| [ ... ], ( ... ), " ... " | creation | |||||
| s + t | concatenation | addition | ||||
| s * n | repetition [a] | multiplication | ||||
| s[i] | indication | |||||
| s[i:k] | slice | |||||
| x in s | membership | |||||
| x not in s | ||||||
| for a in s | iteration | |||||
| len(s) | length | |||||
| min(s) | return smallest element | |||||
| max(s) | return greatest element | |||||
| s[i] = x | index assignment | |||||
| s[i:k] = t | slice assignment | |||||
| del s[i] | deletion | |||||
| ||||||
Table 9.2. List methods
| Method | Operation |
|---|---|
| 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'] | |