This is a list of list methods. In it, L is the list to which the method is applied, M is a list, x is an element to be added to, looked for, or removed from, a list, and i is an index of a list element.
| Operation | Description |
|---|---|
| L.append(x) | Append element x to L |
| L.count(x) | Count the number of times x occurs in L |
| L.extend(M) | Extend L by adding the elements of M at the end |
| L.index(x) | Return the index of the first occurrence of x in L; ValueError exception if x not in L |
| L.insert(i,x) | Insert x at position i in L |
| L.pop() | Remove and return the last element of L |
| L.pop(i) | Remove and return the element of L at position i; IndexError exception if i out of range |
| L.remove(x) | Remove the first occurrence of x from L; ValueError exception if x not in L |
| L.reverse() | Reverse L in place (does not make a copy) |
| L.sort() | Sort L in place (does not make a copy) |
Slicing allows you to extract parts of a list. The general form is:
Here, s is the starting index, e is the index just beyond the end of the slice, and i is the increment.
Here are some examples using the list
Be careful when you are assigning lists! Here’s a code segment that may surprise you when it is executed:
L = [ 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h' ]
X = L
print("Before, X is", X)
print("Before, L is", L)
X[2] = 'x'
print("After, X is", X)
print("After, L is", L)
This prints:
Before, X is ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'] Before, L is ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'] After, X is ['a', 'b', 'x', 'd', 'e', 'f', 'g', 'h'] After, L is ['a', 'b', 'x', 'd', 'e', 'f', 'g', 'h']
Notice that when you change the list X, you also change L. That’s because X is just another name for L.
If you want to make a copy of L, you must do it this way:
L = [ 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h' ]
X = L[:]
print("Before, X is", X)
print("Before, L is", L)
X[2] = 'x'
print("After, X is", X)
print("After, L is", L)
This prints:
Before, X is ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'] Before, L is ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'] After, X is ['a', 'b', 'x', 'd', 'e', 'f', 'g', 'h'] After, L is ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
Here, while X is changed, L is not. So L[:] creates a copy of the list L, which is then given the name (assigned to the variable) X.
|
MHI 289I, Programming in Health Informatics Version of September 16, 2025 at 12:38PM
|
You can also obtain a PDF version of this. |