I was working on a mini project which I intended to use pure Python without any external library.
But at a certain point, I got a TypeError like this TypeError: unsupported operand type(s) for ** or pow(): 'list' and 'int'. It was as a result of trying to directly square up all elements in a list like this:
. Although I have already created a function that could square up the list, but when I tried multiplying a numpy array like this:my_list = [0, 7, 2, 9]print(my_list ** 2)
import numpy as np
my_list = np.array([0, 7, 2, 9])
print(my_list ** 2)# prints array[0, 49, 4, 9]
My question is why does this happen? Or does numpy has a special property that enables it to behave like this?
my_list *2andmy_list+my_listalso have different meanings (cf to numbers andndarray)+,*and**are implemented by methods attached to one or both of the arguments. Numbers most of these, lists and strings only have a few (with different meanings than numbers). Numeric dtype arrays also implement most of these operators. Operators and methods are documented for each class.x*2andx+xhave different meanings? For all builtin numeric types as well as all sequence types these two versions are equivalent and I'd also expect them to be equivalent forndarrayobjects.xbeing a list or string. Same result, but different from numeric calculations