x = (1, 3.33333, "hello", True, 4)Lists
Mutable sequences, represented as values separated with commas and enclosed with square brackets [].
- It is possible to initialize an empty list with
x = []
What can go in?
- Lists and tuples can be a collection of items of any type.
- You can even make tuples of tuples, lists of lists, lists of tuples…
- For example: a 3x3 matrix - a 3-element list of 3-element lists
mat = [[1,2,3],
[4,5,6],
[7,8,9]]
print(mat[0][1]) # accessing value in row 0 and column 12
Changing versus copying
When dealing with mutable objects, it is very important to check if an operation is changing the object or making a copy of it.
For example:
a = [1,2,3]
b = a
a[1] = 5
print(b)[1, 5, 3]
What happened here? Wasn’t
bsupposed to remain[1,2,3]?aandbare pointing to the same object (the list[1,2,3]). If we change something ina, we change inband vice-versa.You can check that with the function
id(), which finds an unique integer identifier for each object.
print(id(a))
print(id(b))140175685109632
140175685109632
It is different if we make a copy of the object.
a = [1,2,3]
b = a.copy()
a[1] = 5
print(a)
print(b)[1, 5, 3]
[1, 2, 3]
- Look at the different ids: they are different objects, and thus are independent of each other.
print(id(a))
print(id(b))140175685143616
140175685057664
- This happens because lists are mutable objects (just as dictionaries, as we’ll see).
- Mutable objects need to be copied. Immutable objects don’t.