When executing the following code

funcdata=[['11'], ['12'], ['13'], ['14'], ['15'], ['16']] masks=[ [0]*3 ]*4 masks[0][0]=funcdata[0][0] print(masks) 

I expect to receive

 [['11', 0, 0], ['0', 0, 0], ['0', 0, 0], ['0', 0, 0]] 

(assign one element a value from another array) but I get:

 [['11', 0, 0], ['11', 0, 0], ['11', 0, 0], ['11', 0, 0]] 

what am I doing wrong?

    2 answers 2

    When you create an array like this:

     masks=[ [0]*3 ]*4 

    You actually create an array of 4 elements that has 4 references to the same element. It's easy to check this way.

     masks=[ [0]*3 ]*4 print(masks) print(id(masks[0])) print(id(masks[1])) print(id(masks[2])) 

    Here is the result:

     [[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]] 4567441352 4567441352 4567441352 

    Alternatively, you can create an array like this:

     funcdata=[['11'], ['12'], ['13'], ['14'], ['15'], ['16']] masks=[ [0]*3 for x in range(0,4)] print(masks) print(id(masks[0])) print(id(masks[1])) print(id(masks[2])) masks[0][0]=funcdata[0][0] print(masks) 

    The result will be:

     [[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]] 4567408328 4568289736 4567486856 [['11', 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]] 
       masks = [[0]*3]*4 

      The contents of your variable in memory look like this:

      enter image description here

      (Cm. Python Tutor .)

      As you can see from the picture, there is only one list in the memory [0, 0, 0] , and the variable masks is a list of four links to it .

      Although from which of these 4 links you work to change the initial list [0, 0, 0] , all these links will show the modified list:

       masks[0][0] = funcdata[0][0] 

      enter image description here