0

I have written a pretty simple code to initialize a matrix, but I'm getting some very unexpected behaviour, this is the exact code that I run:

n = 2
b = [ ([0.0] * n) ] * n
c = [ ([0.0] * n) ] * n   
a = [ [1.0, 2.0, 3.0], [2.0, 1.0, 3.0]]
....
print(c[0])
print(c[1])
for i in range(0, n):
    b[i][0] = a[i][0] #this one is initialized as expected
    c[0][i] = a[0][i] / b[0][0] # notice that c[1] isn't touched here in any way but when I print it out it is initialized to [1.0 1.0]
print("")
print(c[0])
print(c[1])

but these are the results I get from the print statements:

[0.0, 0.0]
[0.0, 0.0]

[1.0, 1.0]
[1.0, 1.0] 

(Only the first row should be initialized, not all of the elements)

I run Python 2.7.2 on Windows. Is there something I'm missing here?

user2268997
  • 1,263
  • 2
  • 14
  • 35

1 Answers1

5

Using the [...] * 3 doesn't create 3 copies but reuses the same object 3 times. So any change to one index will be mirrored to the other:

>>> a = [[1] * 2] * 3
>>> a
[[1, 1], [1, 1], [1, 1]]
>>> a[0][1] = 3
>>> a
[[1, 3], [1, 3], [1, 3]]

It's better to initialise like this:

a = [[1] * 2 for i in range(3)]
JuniorCompressor
  • 19,631
  • 4
  • 30
  • 57