Eric Snow <ericsnowcurren...@gmail.com> added the comment:

In Python, multiplication on a list does not make copies of the values in the 
original list.  So what you have done is equivalent to the following:

  a = [0, 0]
  b = [a, a]
  M = [b, b]

Hence:

  >>> M[0] is M[1]
  True
  >>> M[0][0] is M[0][1]
  True
  >>> M[1][0] is M[1][1]
  True
  >>> M[0][0] is M[1][0]
  True

So the following *all* modify the first value in "a":

  M[0][0][0] = 1
  M[1][0][0] = 1
  M[0][1][0] = 1
  M[1][1][0] = 1

That is why you are seeing the result you reported.  Depending on your needs, 
better solutions include using a list comprehension, spelling out the for loops 
(for readability), a helper function (for complex problems), or simply spelling 
out the full list literal instead of composing it.  Regardless, I highly 
recommend using a solution that is easy for a new reader to understand.  Even 
if no one else will read this code, your six-months-from-now self will thank 
you. :)

----------
nosy: +eric.snow
resolution:  -> not a bug
stage:  -> resolved
status: open -> closed

_______________________________________
Python tracker <rep...@bugs.python.org>
<https://bugs.python.org/issue36450>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com

Reply via email to