how come the output is 12, I still don't really understand how y[0] value was also changed | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

how come the output is 12, I still don't really understand how y[0] value was also changed

y=[5] z=y z[0]+=1 print(y[0]+z[0]) #prints: 12

6th Apr 2022, 10:10 PM
Reymark Marzan
Reymark Marzan - avatar
2 Answers
+ 3
When you say z=y you are not creating a new copy of the list [5]. You are only creating a second name (z) that refers to the same list object as the first name (y). So y[0] and z[0] refer to the same thing, not only the same number originally but the same memory location. If you change z[0] you also change y[0] because they are two references to the same object.
7th Apr 2022, 12:22 PM
Erik
+ 1
Jay Matthews but how y[0] increments too?
6th Apr 2022, 11:01 PM
Reymark Marzan
Reymark Marzan - avatar