Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python's += operator and lists [duplicate]

Tags:

python

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?

like image 637
linkyndy Avatar asked Nov 11 '22 13:11

linkyndy


1 Answers

The a+=b is a shortcut for a.extend(b), not a=a+b .. which, as you've said, creates a new list.

like image 101
eduffy Avatar answered Nov 15 '22 13:11

eduffy