ynonp / python-examples-verint-2016-07

Python examples and exercises
MIT License
2 stars 35 forks source link

Why [ [x] * 3] * 3 is not the same as [[x, x, x], [x, x, x], [x, x, x]] ? #222

Open nirna opened 8 years ago

nirna commented 8 years ago

My python shows both as equal:

>>> [[None] * 3] * 3 == [[None, None, None], [None, None, None], [None, None, None]]
True

Why do you say they're not the same?

ynonp commented 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