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.
... And that's why you learn C first instead of a high level language to understand abstractions later.
It still shows the same problem.
The code should only modify one element, right? Since you modify arr[0][0]. But instead it changes the whole row.
I haven't coded Python in over a year, since my bachelors but you would either have to append the array i think or add a +1 to it.
Sorry user i know not much help got my managment mind on.
Try this might help tutorialgateway.org
The question has been asked and answered here:
stackoverflow.com
I think it has something to do with that for loop
This code :
arr = [[0,0],[0,0],[0,0]]
for x in range(3):
print(arr[x][0])
print("New:")
arr[0][0] = 1
for x in range(3):
print(arr[x][0])
prints:
0
0
0
New:
1
0
0
it's because you multiplied [0] * 2 by 3. it will use the same references as the first element
Oh wait I'm retarded
is correct
What if I want an array with 1000x2000 elements?
>stackoverflow.com
>*deletes your question for being off-topic, and already being asked 13 years ago*
heh, nothing personnel skiddo
this
[[0] * 1000 for _ in range(2000)]