Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
nirna opened this issue Jul 29, 2016 · 1 comment
Open

Comments

@nirna
Copy link

nirna commented Jul 29, 2016

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?

@nirna nirna changed the title Why Why [ [None] * 3] * 3 is not the same as [[None, None, None], [None, None, None], [None, None, None]]? Jul 29, 2016
@nirna nirna changed the title Why [ [None] * 3] * 3 is not the same as [[None, None, None], [None, None, None], [None, None, None]]? Why [ [x] * 3] * 3 is not the same as [[x, x, x], [x, x, x], [x, x, x]] ? Jul 30, 2016
@ynonp
Copy link
Owner

ynonp commented Jul 30, 2016

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants