Code:
a = [1, 2, 3]
b = a
a.append(4)
print(b)
Solution and Explanantion:
a = [1, 2, 3]:
This line creates a list a with elements [1, 2, 3].
b = a:
Here, b is not a new list but a reference to the same list object that a refers to. In Python, variables that hold lists (and other mutable objects) actually hold references to the memory location where the list is stored. So, b now refers to the same list as a.
a.append(4):
This line adds the element 4 to the end of the list a. Since a and b refer to the same list, this modification affects both a and b.
print(b):
Since b refers to the same list as a, the output will show the modified list [1, 2, 3, 4].
Final Output:
[1, 2, 3, 4]
The key concept here is that a and b are references to the same list in memory, so changes to the list via one variable are reflected in the other.
0 Comments:
Post a Comment