Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Different behaviour for list.__iadd__ and list.__add__

Tags:

People also ask

What does list __ add __ do?

The __add__() method in Python is a special method that defines what happens when you add two objects with the + operator.

What is __ add __ in Python?

__add__ magic method is used to add the attributes of the class instance. For example, let's say object1 is an instance of a class A and object2 is an instance of class B and both of these classes have an attribute called 'a', that holds an integer.

What can list () do?

The list() function creates a list object. A list object is a collection which is ordered and changeable.


consider the following code:

>>> x = y = [1, 2, 3, 4]
>>> x += [4]
>>> x
[1, 2, 3, 4, 4]
>>> y
[1, 2, 3, 4, 4]

and then consider this:

>>> x = y = [1, 2, 3, 4]
>>> x = x + [4]
>>> x
[1, 2, 3, 4, 4]
>>> y
[1, 2, 3, 4]

Why is there a difference these two?

(And yes, I tried searching for this).