Is there an explainer on the difference between?
aL, bL = [[], []]
xL, yL = [[]] * 2
Superficially, they should be the same.
[[], []] == [[]] * 2
True
But they behave differently.
aL.append("a")
xL.append("x")
bL
[]
yL
['x']
Is there an explainer on the difference between?
aL, bL = [[], []]
xL, yL = [[]] * 2
Superficially, they should be the same.
[[], []] == [[]] * 2
True
But they behave differently.
aL.append("a")
xL.append("x")
bL
[]
yL
['x']
>>> [[]] * 2 == [[], []] # True
>>> a1, b1 = [[], []]
>>> id(a1) # 4425627680
>>> id(b1) # 4425627760
>>> a2, b2 = [[]] * 2
>>> id(a2) # 4424875616
>>> id(b2) # 4424875616
When you utilize the *
expression to generate a list of lists, Python is copying the inner object of [[]]
, and copying its reference over. Therefore, when doing [[]] * 2
, you end up with a list of lists in which all of the inner lists are the same object. If you are still confused, I recommend checking out this post.
Now why [[]] * 2 == [[], []]
is True, this is easy to observe:
>>> bool([[], []]) # True
>>> bool([[]] * 2) # True
>>> bool([]) # False
A list with anything inside always evaluates to True
, therefore you are doing True == True
which is of course True
.