A Python programmer has written the following code involving lists, tuples and…
2026
A Python programmer has written the following code involving lists, tuples and dictionaries. Go through it carefully and answer the following questions with proper justifications.
a = [1, 2, 3]
b = a
c = a[:]
d = a.copy()
a.append(4)
b[0] = 99
c += [5]
d.insert(1, 0)
t = (1, [2, 3], 4)
t[1].append(5)
print(t)
info = {'name': 'Alice', 'marks': [90, 85, 78]}
info2 = info.copy()
info2['name'] = 'Bob'
info2['marks'].append(95)
print(info)
(i) After all operations, print the values of a, b, c, d. Justify each using Python’s memory model.
(ii) Tuples are immutable. Explain why t[1].append(5) does not raise TypeError. What is the final value of t?
(iii) info.copy() is called yet modifying info2['marks'] also modifies info’s. Explain precisely. How would you fix it?
Show answer & explanation
(i) Final Values with Memory Model Justification
Final Values:
a = [99, 2, 3, 4]
b = [99, 2, 3, 4]
c = [1, 2, 3, 5]
d = [1, 0, 2, 3]
Stepwise Memory Explanation
a = [1,2,3]: A new list object is created in memory.
b = a: Reference assignment (aliasing). Both point to same object (id(a) = id(b)).
c = a[:] , d = a.copy(): Shallow copy. New list objects created (id(c) ≠ id(a), id(d) ≠ id(a)).
Mutation Sequence
a.append(4): In-place modification of original object → [1,2,3,4] (affects both a and b)
b[0] = 99: Same shared object modified → [99,2,3,4]
c += [5]: Independent list modified → [1,2,3,5]
d.insert(1,0): Independent list modified → [1,0,2,3]
(ii) Tuple Immutability
Tuple t = (1, [2,3], 4)
Tuples are immutable in terms of reference binding, not object mutability.
t[1] refers to a list (mutable object).
t[1].append(5) modifies the internal list in-place without changing its reference.
Hence, no TypeError occurs.
Final value:
t = (1, [2, 3, 5], 4)
(iii) Shallow Copy in Dictionary
info.copy() creates a new dictionary but shares references of nested objects.
Thus, list under 'marks' is shared.
Modifying info2['marks'] mutates same list.
Final info:
{'name': 'Alice', 'marks': [90, 85, 78, 95]}
Fix (Deep Copy)
import copy
info2 = copy.deepcopy(info)Conclusion
This problem highlights aliasing, shallow copy, in-place mutation, and deep copy, which are key aspects of Python’s memory model.
A video solution is available for this question — log in and enroll to watch it.