+ 1

Please Explain This Python Code

a = 'Apoorve kumar verma' b = [11,12,13] c = 55 x = [a,b,c] u = x[:] b[1] = 10 print(x[1][1]) #print 10 print(u[1][1]) #print 10 a1 = 'Apoorve kumar verma' b1 = [11,12,13] c1 = 55 x1 = [a1,b1,c1] u1 = x1[:] b1 = [11,14,13] print(x1[1][1]) #print 12 print(u1[1][1]) #print 12 <h2>why it is happend?<h2>

17th Feb 2018, 6:00 AM
Apoorve Kumar Verma
Apoorve Kumar Verma - avatar
3 Answers
+ 6
The first case - you changed an element of the b list, so whenever it's referenced to, it returns the new value of 10. Now x contains b explicitly and u is its shallow copy (preserves references rather than values), so behaves the same. The second case is similar, but you change the reference of the whole list, not just its element. Now both x1 and u1 point to the elements of the "old" b1, but b1 itself has been re-assigned and has nothing in common with its own copy anymore. It is well-explained and graphically illustrated here: https://www.python-course.eu/deep_copy.php
17th Feb 2018, 8:36 AM
Kuba SiekierzyƄski
Kuba SiekierzyƄski - avatar
+ 5
I would also like to know 😗
17th Feb 2018, 6:33 AM
Louis
Louis - avatar
+ 3
Please put in playground
17th Feb 2018, 7:03 AM
Oma Falk
Oma Falk - avatar