What would you expect to be the output of the following code snippet: `a = [1, 2, 3]; b = a; b[1] = 4; print(a); print(b);`, and why?

a = [1, 2, 3] b = a b[1] = 4 print(a) print(b) The output of this would be:[1, 4, 3] [1, 4, 3] This occurs because lists in Python are pass-by-reference, rather than pass-by-value. What this means is that when we assign b to a, we are not copying the list [1,2,3] to b, we are just copying the reference! So when we change the second element of b to 4, then print a and b, both of them print [1,4,3], because both of them point to the same list.

Answered by Ibrahim Q. Python tutor


See similar Python Mentoring tutors