What happened when I wrote a, b, c = [[],] * 3
in python?
It seems that a
, b
, c
are the same object.
a, b, c = [[],] * 3
a.append(1)
b.append(2)
print(c)
The answer is [1,2]
, why?
What happened when I wrote a, b, c = [[],] * 3
in python?
It seems that a
, b
, c
are the same object.
a, b, c = [[],] * 3
a.append(1)
b.append(2)
print(c)
The answer is [1,2]
, why?
The *
operator just creates copies of the same list []
three times, not three fresh lists.
So, a
, b
, c
all point to the same list. And you added 1
and 2
to both.
This:
a, b, c = [[] for _ in range(3)]
a.append(1)
b.append(2)
print(c)
would give you []
as expected.