Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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)

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading