I’m learning about Python (version 2.4.2 if that makes any differences), but I’ve come across something that doesn’t seem to do what I want it to do.
I gather that a += b, for example, is the equivalent of a = a + b. This seems to work for numbers, thus:
>>> a = 3
>>> a += 2
>>> print a
>>> 5
However, it seems to do odd things when you have lists of lists. For example:
>>> a = [[9]]*10
>>> print a
[[9], [9], [9], [9], [9], [9], [9], [9], [9], [9]]
>>> a[5] += [3]
>>> print a
[[9, 3], [9, 3], [9, 3], [9, 3], [9, 3], [9, 3], [9, 3], [9, 3], [9, 3], [9, 3]]
>>>
What I would expect a[5] += [3] to do is append 3 to the 6th entry in a, to make a[5] = [9.3], and the other entries equal to [9]. However, it appears here to append it to all the lists in a.
Is this just a quirk in Python, or something I’m doing wrong? Can I use += in this way to do what I want, and/or is there another (better) way of doing it?
To clarify, what I want to do sometimes involves appending more than one element to lists, such as appending 3 and 4, to get [9,3,4].