+1

Why did we get this kind of output in the following two codes mentioned below ? Can any one explain me clearly...

-------------------- 1st code : ------------------- l1=[1,33,12,42] l2=l1 l1[2]=1 print(l2[1]+l2[2]) And the output is 34. Why ? And also can anyone say why the output is not 45 and how did the change in list "l1" reflect or effect the list "l2" ------------------ 2nd code : ------------------ a=1 b=a a=2 print(b) And this code is different from the output of above code i.e., it gives the output as 1 but not 2. Why ? And also can anyone say why the change in the value of variable "a" didn't effect the value in variable "b"... If you want then see the code which I have mentioned below and execute each of them putting the corresponding one in multiline comments... https://code.sololearn.com/cDPb8nmTR9HU/?ref=app

9/8/2019 10:11:09 AM

Kiran Deep Naidu

2 Answers

New Answer

+3

Lists are passed as references, unlike normal values like numbers. So, when you created l1, there was a list [1, 33, 12, 42] allocated in the memory, and now l1 'points' to it. When you assign l1 to l2, you just give them the same reference, meaning if you change that, the other one will change too. But, normal values are passed by value, so b = a means b gets assigned a's value, which is 1. It doesn't care if a changes.

+1

1. When you change l1[2], you also change l2[2] as well because they are copies of the same list. 2. You set b=a when a=1. Then you set a=2 and print b, but b still equals 1.