0
Value of first list changes even if I'm only appending to the second list referencing to the first one
I'm making a code that checks wether its Geometric Sequence or not and output its common ratio. This is where the problem is, the length of nums_n after this should be 4 since I'm appending to it. But the list nums also becomes the same as nums_n, this shouldn't happen, should it? nums_n = nums nums_n.append(nums[-1]*supposed_r) print(nums) https://code.sololearn.com/cf1gvR7fHfoe/?ref=app
5 Antworten
+ 2
nums_n = nums
This line makes two list object point to same location ,and any change to elements in either list changes both
if you don't want that behaviour create a new list object and then assign it to nums_n,
nums_n=list(nums)
+ 2
Abhay Thank you very much this will be useful
+ 1
Abhay Just a quick question regarding this
Does it only apply to list? I tried to recreate it on integers
a = 1
b = a
b += 1
But a still remains 1
Thank you very much
+ 1
ăăă§ă anything that is assigned is pointing to same location but the changes to both when changing one only applies for mutable objects unlike strings and int which are not mutable and any operation you do like b+=1 results in creation of new int object (b) with different location than the previous one(b),
You can confirm what I said and get a better understanding by using a function called id which returns a integer number indicating where that value is stored in memory
Use it like this :-
print(id(variable-name))