If you add an integer to a list, you get an error raised by the __add__ function of the list (I suppose):
>>> [1,2,3] + 3
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can only concatenate list (not "int") to list
If you add a list to a NumPy array, I assume that the __add__ function of the NumPy array converts the list to a NumPy array and adds the lists
>>> np.array([3]) + [1,2,3]
array([4, 5, 6])
But what happens in the following?
>>> [1,2,3] + np.array([3])
array([4, 5, 6])
How does the list know how to handle addition with NumPy arrays?
[1,2,3].__add__(np.array([3]))will fail, but Python reverses the arguments if the first attempt fails andnp.array([3]).__radd__([1,2,3])(__add__is called if__radd__isn't defined) works.__radd__be called?a + bwill ever callb.__add__. Python doesn't assume that addition is commutative. You may be thinking of the augmented assignment operators, wherea += bwill first trya.__iadd__, but then fall back to__add__(and further tob.__radd__) if necessary.