I though that a += b
is just a shortcut for a = a + b
. It seems it is not quite. Here's an example:
>>> a = [1, 2, 3]
>>> b = a
>>> b += [4, 5, 6]
>>> b
[1, 2, 3, 4, 5, 6]
>>> a # is also changed
[1, 2, 3, 4, 5, 6]
But this works as expected:
>>> a = [1, 2, 3]
>>> b = a
>>> b = b + [4, 5, 6]
>>> b
[1, 2, 3, 4, 5, 6]
>>> a # not changed
[1, 2, 3]
Now, I understand that when I do b = a
, b
references the same list as a
does, and if I do some operations on b
, they automatically "apply" to a
(since they both point to the same list, and that when I do b = b + [4, 5, 6]
a new list is created and then assigned to b
, but my question is...why this distinction? I mean, shouldn't a += b
be a shorthand for a = a + b
? This is what one would have expected...What's the logical explanation for this?
The a+=b
is a shortcut for a.extend(b)
, not a=a+b
.. which, as you've said, creates a new list.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With