Hello Jow Forums, do you know Python?
If so, then why does the following code:
arr = [[0] * 2] * 3
[print (arr [x][0]) for x in range (3)]
arr [0][0] = 1
print ("New:")
[print (arr [x][0]) for x in range (3)]
print:
0
0
0
New:
1
1
1
?
Hello Jow Forums, do you know Python?
If so, then why does the following code:
arr = [[0] * 2] * 3
[print (arr [x][0]) for x in range (3)]
arr [0][0] = 1
print ("New:")
[print (arr [x][0]) for x in range (3)]
print:
0
0
0
New:
1
1
1
?
I think it has something to do with pointers
How to deal with pointer in python?
You can't
Well what is it meant to print?
0 x 2 = 0 x 3 = 0
It'll print 0 three times since you have set the range to 3
You then set the array to 1 so it will print out 1 3 times?
I don't set the array:
arr[0][0] = 1
sets only the first element of the first row and column
1
0
0
Because you didn't make a deep copy. It would be inefficient to do that automatically.
Here user, im not sure what you're trying to do but you're just making it print out the value you have posted
To complete my answer, look up the concept of reference counting. Instead of copying the content of the object itself, you just copy its address to save memory and cpu cycles. This way there will be several references pointing to the same memory area.