Skip to content
Advertisement

Why Doesn’t This Throw an Unsupported Operand Error?

With the code below, I would have expected the X.extend line to throw an unsupported operand error (TypeError: unsupported operand type(s) for +: ‘float’ and ‘list’) since a float is trying to be added to a list. But it runs and gives the same answer as Y.extend, where the entire expression is bracketed as a list. I am using Python 3.10. Now, if you replace the np.cos(fwd_angle) term in X.extend with its actual value (0.5), then python throws the expected error. Why does the initial code work without throwing an error?

import numpy as np

X = [1., 2., 3.]
Y = [1., 2., 3.]
fwd_angle = 60.*np.pi/180.

for i in range(3):
    X.extend( X[i + 1] * np.cos(fwd_angle) + [X[i] + np.sin(fwd_angle)] )
    Y.extend( [Y[i + 1] * np.cos(fwd_angle) + Y[i] + np.sin(fwd_angle)] )

print(X)
print(Y)

Advertisement

Answer

np.cos doesn’t return a float value; it returns a numpy.float64 value. These can be added to lists, and the result is a numpy.ndarray value.

numpy.float64.__add__ works by adding the invoking object to each element of an arbitrary iterable:

 # [-1 + 1, -1 + 2, -1 + 3]
 >>> np.cos(np.pi) + [1,2,3]
 array([0., 1., 2.])

(Also, the product of a float and an numpy.float64 value is also a numpy.float64 value.)

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement