-1

I was trying add ones to some specific position in a 100*100 zero matrix. My code was something this:

adjacency=[[0]*100]*100
while ...
    x=...
    y=...
    adjacency[x][y]=adjacency[x][y]+1

But it adds to other positions as well. In face, adjacency[0]=adjacency[1]=..=adjacency[99], while there's no way that the calculation of x, y in while-loop will produce this kind of result.

So, I changed to array. The only thing I changed was:

adjacency=np.zeros((100,100))

And the result is right this time. Adjacency[i] no longer equals to each other.

Does anyone know why? (Using Python2.7.)

2 Answers2

1

The * operator is not always a good thing for creating lists, specially multi-dimensional lists. This operator just creates copies of the elements in the list to populate the larger list. This works fine for primitive types, but not for other objects.

For example, when you write [0] * 100, it creates a list of 100 elements and assigns 0 to each item. Now you have the reference of a 100-element list. So when you write [[0] * 100] * 100], you get a list of 100 references of the list [0] * 100. So when you change a value, it affects all the 'rows', because all the rows are referencing the same list.

Here's a smaller example:

>>> a = [0] * 3
>>> print a
[0, 0, 0]
>>> b = [a] * 2
>>> print b
[[0, 0, 0], [0, 0, 0]]
>>> a[0] = 1
>>> print a
[1, 0, 0]
>>> print b
[[1, 0, 0], [1, 0, 0]]
>>> b[0][1] = 2
>>> print b
[[1, 2, 0], [1, 2, 0]]
Sufian Latif
  • 13,086
  • 3
  • 33
  • 70
0

The first row list is copied every time to the 99 other positions. You need to create a new list for each row, something like this:

adjacency=[[0] * 100 for y in range(100)]
vz0
  • 32,345
  • 7
  • 44
  • 77