Lists

Mutable sequences, represented as values separated with commas and enclosed with square brackets [].

What can go in?

  • Lists and tuples can be a collection of items of any type.
x = (1, 3.33333, "hello", True, 4)
  • 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 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:

a = [1,2,3]
b = a
a[1] = 5
print(b)
[1, 5, 3]
  • What happened here? Wasn’t b supposed to remain [1,2,3]?

  • a and b are pointing to the same object (the list [1,2,3]). If we change something in a, we change in b 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.

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.