1

thanks for taking time to answer the question. I am confused here as to why the outputs do not match.

Operation 1:

x = [[0, 0], [0, 0]]
print(type(x)) # <class 'list'>
print(x) # [[0, 0], [0, 0]]

x[0][0] = 1
print(x) # [[1, 0], [0, 0]]

Operation 2:

y = [[0] * 2] * 2
print(type(y)) # <class 'list'>
print(y) # [[0, 0], [0, 0]]

y[0][0] = 1
print(y) # [[1, 0], [1, 0]]

My understanding was that both x and y should be the same. But looks like they are not. What am I missing here?

waka-waka-waka
  • 1,025
  • 3
  • 14
  • 30

1 Answers1

6

What you're missing is that when you do this:

y = [[0] * 2] * 2

You have created a single list [0] then [0, 0]. Call this list X. Then you created [X, X] where both X's point to the same underlying list. So when you modify the first list the second one is modified too.

Why doesn't modifying the first element of the first list also modify the second element of each list? Well, that's because [0] * 2 really is a list of two numbers, because a reference to 0 cannot be modified (imagine the horrors if your program's 0 meant something else!).

John Zwinck
  • 239,568
  • 38
  • 324
  • 436
  • In the future, please consider marking the question as a duplicate, as such duplicates often contain much better, more complete answers than one poster can possibly provide in four minutes. – TigerhawkT3 Aug 10 '16 at 05:54