= (1, 3.33333, "hello", True, 4) x
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
= [[1,2,3],
mat 4,5,6],
[7,8,9]]
[print(mat[0][1]) # accessing value in row 0 and column 1
2
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:
= [1,2,3]
a = a
b 1] = 5
a[print(b)
[1, 5, 3]
What happened here? Wasn’t
b
supposed to remain[1,2,3]
?a
andb
are pointing to the same object (the list[1,2,3]
). If we change something ina
, we change inb
and 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.
= [1,2,3]
a = a.copy()
b 1] = 5
a[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.