Code Explanation:
Line 1: x = [[]] * 2
What happens?
[] creates an empty list.
[[]] creates a list containing one empty list.
* 2 duplicates the reference to the inner list, not the list itself.
Memory Representation
x
│
├──► []
└──► []
Both x[0] and x[1] point to the same inner list.
Value of x
[[], []]
Line 2: x[0].append(1)
What happens?
x[0] refers to the shared inner list.
append(1) adds 1 to that list.
Memory Representation
x
│
├──► [1]
└──► [1]
Since both positions reference the same list, both appear updated.
Value of x
[[1], [1]]
Line 3: print(x)
What happens?
Python prints the contents of x.
Output
[[1], [1]]
Why This Happens
List Multiplication (*)
x = [[]] * 2
creates:
x[0] ──┐
├──► []
x[1] ──┘
Both elements point to the same list object.
Final Output
[[1], [1]]

0 Comments:
Post a Comment