Dark theme

Key ideas in depth: Container manipulation


Here we look in a bit of depth at operations that treat containers like mathematical entities. In general, these are confusing to people who don't know what they do, so we'd advise against using them, but it's worth understanding them incase you see other code that uses them.


We've seen that you can do maths on tuples:
>>> a = 1,2,3
>>> a = a + (4,) # or a += 4
>>> a
(1, 2, 3, 4)

>>> a = 1,2,3
>>> a = a*2 # a *= 2 only works with single values.
>>> a
(1,2,3,1,2,3)

However, things become more complicated with lists: the references are copied, not the actual objects linked to, so:
>>> a = [[1,2],[10,20]]*2
>>> a
[[1,2],[10,20] [1,2],[10,20]]
This seems like it has worked as with tuples, however, as the internal lists are mutable, changing them doesn't make a new object (as it would with a number or string):
>>> a[0][0] = 100
>>> a
[[100,2],[10,20] [100,2],[10,20]]
Given this, avoid creating lists this way unless this is absolutely what you are trying to exploit. An alternative can be found in the documentation, though it requires some info on loops we'll deal with later in the course.


While we're on the subject, remembering what happens with labels, it is worth saying that this doesn't copy a list:
>>> a = [1,2,3,4,5,6]
>>> b = a

b and a are the same thing.
However, slices return a "shallow copy" of the list. This means they copy the list, and each object reference inside it.
>>> a = [1,2,3,4,5,6]
>>> b = a[:] # can also use a.copy()
If the objects inside are immutable (numbers, tuples), changing them will replace them with new numbers.
>>> b[0] = 10
>>> a
[1,2,3,4,5,6]
>>> b
[10,2,3,4,5,6]

But if they are mutable, the object linked to will change, so beware.


In theory, as well as the stuff above, you can also do mathematical and other comparisons on sequences. However, the results are not always intuitive, so these are best avoided:

a = (1,2,3,4)
b = (1,2,3)
4 in a # True
5 not in a # True
b in a # False; a doesn't contain any tuples.
a == b # False

a > b # True, as b the same but shorter.

But, avoid using > or <, for example:
a = (2,2,2,2,2,2)
b = (6,6)
b > a # True because first thing greater.
Sequences are evaluated a value at a time left to right until the first reasonable answer is reached.

In theory, you can compare sequences, but generally it's to be avoided; the results are complicated to determine.