Open nirna opened 8 years ago
Fascinating!. Here's the short explanation in code (and later in english):
>>> a = [[None] * 3] * 3
>>> a[0][0] = 'a'
>>> a
[['a', None, None], ['a', None, None], ['a', None, None]]
Turns out Python's * n
operator creates a new reference to the same structure, instead of creating a new list. Thus every change to the original list reflects in all 3 lists which breaks the game.
The solution is to use list comprehension, which causes python to create new lists as described here: http://stackoverflow.com/questions/6688223/python-list-multiplication-3-makes-3-lists-which-mirror-each-other-when
And the code:
self.data = [[None] * 3 for x in range(3)]
The above runs the [None] * 3
expression 3 times, each time creating a new list
My python shows both as equal:
Why do you say they're not the same?