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?

JavaScript

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:

JavaScript

(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