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:
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]
np.ndarray
defines its own dunder methods for operators such as__pow__
. That's how it manages to handle those operations elementwise. With builtin lists you can use a list comprehension instead:您还可以定义自己的类来暴露此类自定义行为: