Why Numpy treats a+=b and a=a+b differently

后端 未结 2 441
挽巷
挽巷 2021-01-03 19:53

Is the following numpy behavior intentional or is it a bug?

from numpy import *

a = arange(5)
a = a+2.3
print \'a = \', a
# Output: a = 2.3, 3.3, 4.3, 5.3,         


        
2条回答
  •  执笔经年
    2021-01-03 20:49

    @aix is completely right. I just wanted to point out this is not unique to numpy. For example:

    >>> a = []
    >>> b = a
    >>> a += [1]
    >>> print a
    [1]
    >>> print b
    [1]
    >>> a = a + [2]
    >>> print a
    [1, 2]
    >>> print b
    [1]
    

    As you can see += modifies the list and + creates a new list. This hold for numpy as well. + creates a new array so it can be any data type. += modifies the array inplace and it's not practical, and imo desirable, for numpy to change the data type of an array when array content is modified.

提交回复
热议问题