Reputation: 32
I don't know whether this is a bug, or I got a wrong semantic meaning of the * token in arrays:
>>> arr = [None] * 5 # Initialize array of 5 'None' items
>>> arr
[None, None, None, None, None]
>>> arr[2] = "banana"
>>> arr
[None, None, 'banana', None, None]
>>> # right?
...
>>> mx = [ [None] * 3 ] * 2 # initialize a 3x2 matrix with 'None' items
>>> mx
[[None, None, None], [None, None, None]]
>>> # so far, so good, but then:
...
>>> mx[0][0] = "banana"
>>> mx
[['banana', None, None], ['banana', None, None]]
>>> # Huh?
Is this a bug, or did I got the wrong semantic meaning of the __mult__
token?
Upvotes: 0
Views: 1576
Reputation: 421
You're copying the same reference to the list multiple times. Do it like this:
matrix = [[None]*3 for i in range(2)]
Upvotes: 1