Re: Is this a bug?

Andrew KUCHLING (fnord@marge.cs.mcgill.ca)
24 Jan 1995 14:07:04 GMT

graham.matthews@maths.anu.edu.au wrote:
: s1 = [ ["a"] * m ] * n

Here's the problem. You're intending s1 to contain n lists, each
containing the string "a" m times. However, what the code above is
actually doing is creating a list of references to an m-element list.
Let's try this for m=3, n=2:

>>> s1= [ ["a"] * m ] * n
>>> s1
[['a', 'a', 'a'], ['a', 'a', 'a']]

It looks like there are 2 different lists, but...

>>> s1[0].append("a")
>>> s1
[['a', 'a', 'a', 'a'], ['a', 'a', 'a', 'a']]

Changing one list changed them all. To reinforce this
important point, let's change the first item of one of the sublists:

>>> s1[0][0]='b'
>>> s1
[['b', 'a', 'a', 'a'], ['b', 'a', 'a', 'a']]

Since behaviour like this probably isn't what you want, you
should be careful to create distinct copies of the list, probably by
using a for loop:

>>> s1=[]
>>> for i in range(0,2): s1.append(["a", "a"])
...
>>> s1
[['a', 'a'], ['a', 'a']]
>>> s1[0].append("b")
>>> s1
[['a', 'a', 'b'], ['a', 'a']]

Hope this helps!

Andrew Kuchling
fnord@binkley.cs.mcgill.ca
andrewk@dexotek.ca