I want to define a function that determines whether an input to a function is a numpy array or list or the input is none of the two mentioned data types. Here is the code:
def test_array_is_given(arr = None):
if arr != None:
if type(arr) in [np.ndarray, list]:
return True
return False
input_junk = 12
input_list = [1,2,3,4]
input_numpy = np.array([[1,2,3],[4,5,6]])
print(test_array_is_given(input_junk))
print(test_array_is_given(input_list))
print(test_array_is_given(input_numpy))
And here is what I get:
False
True
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
/var/folders/gv/k2qrhzhn1tg5g_kcrnxpm3c80000gn/T/ipykernel_1992/766992758.py in <module>
12 print(test_array_is_given(input_junk))
13 print(test_array_is_given(input_list))
---> 14 print(test_array_is_given(input_numpy))
/var/folders/gv/k2qrhzhn1tg5g_kcrnxpm3c80000gn/T/ipykernel_1992/766992758.py in test_array_is_given(arr)
1 def test_array_is_given(arr = None):
----> 2 if arr != None:
3 if type(arr) in [np.ndarray, list]:
4 return True
5 return False
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
As you can see, I set the default value for argument arr
to be None
. However, whenever I try to evaluate the function given a numpy array, it faces the above error.
Any ideas on how to resolve this? Thank you for your attention in advance.