+ 1
Why does the variable array change
array = [1,2,3,4,5] a = array a.pop(0) print(array) [2, 3, 4, 5] When you run this in python the lower array will be the output. Why is that the case? Since I'm only using pop on a, why would the array variable change accordingly?
4 Antworten
+ 1
As others have explained, a does not actually get the content of the array. It gets the address location (reference) of the array. And so any changes made to a is also made to the array...
A quick fix to this is to pretend to slice the original array. a = array[:]. With this the original array will not be affected.
You can also check out the other fixes in this stackoverflow thread
https://stackoverflow.com/questions/29785084/changing-one-array-changes-another-in-JUMP_LINK__&&__python__&&__JUMP_LINK
+ 2
Thank you guys!!
+ 1
it should have something to do with referencing.When an object is created from another changes to one object will affect the other
+ 1
Array is a pointer. If you make any variable is equal to this pointer then the pointers is copied(not arrays).