0

I have encountered a strange behaviour of python

Case-1:- arr=[[0]*2]*3 and arr[0][0]=12 gives arr as [[12, 0], [12, 0], [12, 0]]

Case-2:- arr=[[0, 0], [0, 0], [0, 0]] and arr[0][0]=12 gives arr as [[12, 0], [0, 0], [0, 0]]

Why this type of behaviour?

1 Answers1

0

I wouldn't have been able to tell you this before seeing your question, but this code:

arr=[[0]*2]*3

is obviously creating the list [0, 0], and then creating an outer list containing 3 references to that same single inner list. So when you set arr[0,0], your setting the first element of that one inner list that is referenced three times.

Your second example, on the other hand, produces an outer list with three unique inner lists.

CryptoFool
  • 21,719
  • 5
  • 26
  • 44