+ 1
Assigns values Python
I know this is simple! but can someone explain this for me why assigning a to b after this a = [2,4,6,8] b = a b[0]=7 a[3]=9 b.append(5) print(a) print(b) both a & b have same values ???
6 Respostas
+ 4
Yes, the have the same values.
Because when you write "b=a" you actually pointed b to the same place in memory as a and that is mean that every change you will do in a will have effect on b, and every change you will change in b will have effect on a.
+ 7
a&b are variables that are pointers to the same object.
If you let b=list(a), they would point to different objects with the same value instead.
Then Mahdi Moradi, the outputs will be different.
+ 6
KfirWe look at my solution and it is actually easier that way :)
+ 4
Mahdi Moradi
a=[2,4,6,8]
b=[]
for i in a:
b.append(i)
a[0]=3
b[3]=5
b.append(10)
print(a)
print(b)
Now the a and b don't point to the same place in memory and the output will be diffrent.
+ 4
Prometheus 🇸🇬
Ohh you right, b=list(a) more easier and effective😁
+ 1
KfirWe
what to do to stop that? and have different values at the end?