+ 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?

11th Apr 2018, 10:34 PM
sam
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
11th Apr 2018, 11:52 PM
cyk
cyk - avatar
+ 2
Thank you guys!!
12th Apr 2018, 7:50 AM
sam
+ 1
it should have something to do with referencing.When an object is created from another changes to one object will affect the other
11th Apr 2018, 10:50 PM
᠌᠌Code X
᠌᠌Code X - avatar
+ 1
Array is a pointer. If you make any variable is equal to this pointer then the pointers is copied(not arrays).
11th Apr 2018, 11:39 PM
Bartosz Pieszko
Bartosz Pieszko - avatar