0

To manually initially an N x N list of 0 values, you can do the following

mylist = [[0 for x in range(n)] for y in range(n)]

Printing a 3x3 version you'd see:

>>> mylist = [[0 for x in range(3)] for y in range(3)]
>>> print(mylist)
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]

Change any value, all good:

>>> mylist[0][1] = 1
>>> print(mylist)
[[0, 1, 0], [0, 0, 0], [0, 0, 0]] 

Now, I know you can initialize a size N list with:

 mylist = [0] * n

And to create an NxN the following appears to work (same 3x3 example)

>>> mylist = [[0] * 3] * 3
>>> print(mylist)
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]

However, modifying this list produces unexpected results

>>> mylist[0][1] = 1
>>> print(mylist)
[[0, 1, 0], [0, 1, 0], [0, 1, 0]] 

Can someone explain why the second way of initializing the NxN list acts in this manner?

Ray
  • 40,256
  • 21
  • 101
  • 138
  • 1
    Thanks for pointing me to the answer--for some reason I couldn't find it searching! – Ray Mar 09 '17 at 22:28
  • It is a weird duplicate to find, glad I helped! – Dimitris Fasarakis Hilliard Mar 09 '17 at 22:29
  • Essentially, you should always expect python to be working with references. – juanpa.arrivillaga Mar 09 '17 at 22:29
  • I see, the inner intialization is a bunch of integer 0's but the outer is a bunch of references to the inner list. – Ray Mar 09 '17 at 22:32
  • @Ray the "inner initialization" is creating a list of 3 references to the same Python `int` object. So, it's working exactly the same. – juanpa.arrivillaga Mar 09 '17 at 22:36
  • @juanpa.arrivillaga yes, just discovered the real difference is the `list` is mutable, vs the `int` which is immutable, so modifying the `int` in this case gives the illusion you're changing it, but your not, you're getting a reference to a new `int`, whereas a mutable object (like a list) would just change, keeping the same reference – Ray Mar 09 '17 at 22:39

0 Answers0