+ 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
1 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.