Different behaviour for list.__iadd__ and list.__add__
__iadd__
mutates the list, whereas __add__
returns a new list, as demonstrated.
An expression of x += y
first tries to call __iadd__
and, failing that, calls __add__
followed an assignment (see Sven's comment for a minor correction). Since list
has __iadd__
then it does this little bit 'o mutation magic.
The first mutates the list, and the second rebinds the name.
1)'+=' calls in-place add i.e iadd method. This method takes two parameters, but makes the change in-place, modifying the contents of the first parameter (i.e x is modified). Since both x and y point to same Pyobject they both are same.
2)Whereas x = x + [4] calls the add mehtod(x.add([4])) and instead of changing or adding values in-place it creates a new list to which a points to now and y still pointing to the old_list.