0

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?

user2804578
  • 32
  • 1
  • 4

1 Answers1

1

You're copying the same reference to the list multiple times. Do it like this:

matrix = [[None]*3 for i in range(2)]

Ben
  • 421
  • 3
  • 10
  • So, then what's exactly the meaning of the `*` token? If it does copy the reference of an object, then I should expect that, on the first part, when passing `arr[2] = "banana"`, the list should be `['banana', 'banana', 'banana', 'banana', 'banana']` and not that one above. – user2804578 Sep 22 '13 at 17:02
  • Oh, just bumped to the answer [elsewhere on StackOverflow](http://stackoverflow.com/questions/9658459/initializing-matrix-in-python-using-0xy-creates-linked-rows/9658522#9658522) However, I find it quite odd that the `*` token doesn't have the same meaning on list as for other elementary data types – user2804578 Sep 22 '13 at 17:08
  • It actually does have the same meaning. It's just that for immutable types, doing things like "copying" always make a new object that's assigned the same value, whereas mutable objects just have their reference copied. Here's some more good reading on what it means for a type to be immutable. http://stackoverflow.com/questions/8056130/immutable-vs-mutable-types-python – Ben Sep 22 '13 at 17:19