Any idea why subtract not working in python ?

cars = [“1”, “2”, “3”]

result = cars[2] - cars[1]

print(result)

Any idea why subtract not working in python ?

cars = [“1”, “2”, “3”]

result = cars[2] - cars[1]

print(result)

import numpy as np

cars = np.array([“1”, “2”, “3”])

result = np.subtract(cars[2], cars[1])

print(result)

Also not working

Because `"1"`

and `"2"`

are string literals, not numbers. Suppose I had the string `"spam"`

and tried to subtract the string `"eggs"`

. What would be the result? Well, it would be an error, since it doesn’t really make sense to “subtract” an arbitrary string from another arbitrary string. If you know your string represents an integer or a float, you can convert it using `int("1")`

or `float("1")`

respectively; with numpy, you can convert arrays between types using `.astype()`

, e.g. `cars.astype(int)`

would convert your array to integer numbers. Of course, if you are defining the lists/arrays yourself as you show above, you should simply define them as numbers to begin with (no `""`

). Make sense?

For more information, I suggest you read the beginner tutorial which is primary concerned with these data types and calculations between them, and more about basic data types for more details. Numpy also has a tutorial on its basic data types, which differ markedly from the native Python ones once beyond basic usage.

Best of luck!

2 Likes