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?

1 Answer 1

1

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

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

Sign up to request clarification or add additional context in comments.

3 Comments

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.
Oh, just bumped to the answer elsewhere on StackOverflow However, I find it quite odd that the * token doesn't have the same meaning on list as for other elementary data types
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. stackoverflow.com/questions/8056130/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.