[i*matrix for i in arr]
The list above is a list of matrices, so when using the sum, it will add arrays.
In [6]: matrix = np.array([[1,2],[3,4]]) In [7]: matrix Out[7]: array([[1, 2], [3, 4]]) In [9]: [i * matrix for i in (2,4,8)] Out[9]: [array([[2, 4], [6, 8]]), array([[ 4, 8], [12, 16]]), array([[ 8, 16], [24, 32]])]
Please check the help for np.sum
File: /home/ale/.virtualenvs/ml/local/lib/python2.7/site-packages/numpy/core/fromnumeric.pyaxis=None, dtype=None, out=None, keepdims=False) Docstring: Sum of array elements over a given axis. Parameters ---------- a : array_like Elements to sum. axis : None or int or tuple of ints, optional Axis or axes along which a sum is performed. The default (`axis` = `None`) is perform a sum over all the dimensions of the input array. `axis` may be negative, in which case it counts from the last to the first axis. .. versionadded:: 1.7.0
It says that if you do not define an axis, it will be summed over all dimensions. Example:
In [4]: np.sum(np.array([[1,2],[3,4]])) # 1 + 2 + 3 + 4... Out[4]: 10
Why does np.sum take longer? that in the expression [i*matrix for i in arr] you create a new array for each i , which then np.sum will sum over all arrays.
There may be other reasons, but I guess that is.