[Numpy-discussion] np.float64 * Python list vs np.float64 + Python list
Bas Swinckels
bas.swinckels at gmail.com
Sat Nov 1 14:28:40 EDT 2014
Hi group,
I just answered a question on Stackoverflow from some new user, who was
bitten by some unexpected behavior when using a list instead of a np.array,
see here:
http://stackoverflow.com/q/26690480/2647279
The unexpected thing that triggered the error is that multiplying a list
with a Numpy scalar behaves like standard integer multiplication of a list
as in Python without raising an error, while addition in the same way works
as expected:
In [1]: import numpy as np
In [2]: np.version.version
Out[2]: '1.8.2'
In [3]: 2 * [1, 2, 3]
Out[3]: [1, 2, 3, 1, 2, 3]
In [4]: 2.5 * [1, 2, 3]
[...]
TypeError: can't multiply sequence by non-int of type 'float'
In [5]: np.float64(2.5) * [1, 2, 3] # like standard Python list tiling
Out[5]: [1, 2, 3, 1, 2, 3]
In [6]: np.float64(2.5) + [1, 2, 3] # element-wise addition
Out[6]: array([ 3.5, 4.5, 5.5])
I would have expected that the multiplication would have either raised an
exception, or would have given the element-wise result np.array([2.5, 5.0,
7.5]). Is there any good reason why multiplication and addition behave so
different? I am using standard, up-to-date python2.7/numpy under 64-bit
Ubuntu 14.04.
Cheers,
Bas
More information about the NumPy-Discussion
mailing list