Explanation:
Creating the List
a = [[]] * 2
Explanation
[] creates an empty list.
[[]] creates a list containing one empty list.
* 2 duplicates the reference to that inner list.
It does not create two different inner lists.
Both a[0] and a[1] point to the same list object.
Value of a
[[], []]
Note: It looks like two lists, but both refer to the same inner list.
Appending an Element
a[0].append(1)
Explanation
a[0] accesses the first inner list.
.append(1) adds the value 1 to that list.
Since a[1] points to the same inner list, it is updated as well.
Value of a
[[1], [1]]
Printing the Result
print(a)
Explanation
print() displays the contents of the list.
Both elements contain [1] because they reference the same inner list.
Output
[[1], [1]]
Why This Happens
The * operator copies references, not the actual nested list.
There is only one inner list in memory.
Any modification made through one reference is visible through the other reference.
Correct Way to Create Independent Lists
a = [[] for _ in range(2)]
a[0].append(1)
print(a)
Output
[[1], []]

0 Comments:
Post a Comment