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

13th Sep 2019, 4:51 PM
Mahdi Moradi
Mahdi Moradi - avatar
6 Answers
+ 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.
13th Sep 2019, 4:57 PM
KfirWe
KfirWe - avatar
+ 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.
13th Sep 2019, 5:04 PM
👑 Prometheus 🇸🇬
👑 Prometheus 🇸🇬 - avatar
+ 6
KfirWe look at my solution and it is actually easier that way :)
13th Sep 2019, 5:07 PM
👑 Prometheus 🇸🇬
👑 Prometheus 🇸🇬 - avatar
+ 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.
13th Sep 2019, 5:06 PM
KfirWe
KfirWe - avatar
+ 4
Prometheus 🇸🇬 Ohh you right, b=list(a) more easier and effective😁
13th Sep 2019, 5:11 PM
KfirWe
KfirWe - avatar
+ 1
KfirWe what to do to stop that? and have different values at the end?
13th Sep 2019, 5:00 PM
Mahdi Moradi
Mahdi Moradi - avatar