I want to know if an array is already defined somewhere before in the code.
Something like a.exist()
gives True if it exists and False if it doesn't.
I tried a.size:
, but if the array doesn't exist yet, it gives an error message, which I want to avoid.
The situation demanding this happened in a loop, if you are wondering.
Using Numpy array, we can easily find whether specific values are present or not. For this purpose, we use the “in” operator. “in” operator is used to check whether certain element and values are present in a given sequence and hence return Boolean values 'True” and “False“.
__array_interface__ A dictionary of items (3 required and 5 optional). The optional keys in the dictionary have implied defaults if they are not provided. The keys are: shape (required) Tuple whose elements are the array size in each dimension.
You'll need to use a try/except block:
try:
_ = a.shape
except NameError:
print('a does not exist.')
except AttributeError:
print('a does not have a shape property.')
As @padraic points out, this really shouldn't occur in the first place. It is best to initialize your variables (e.g. a = None
) and then check that they have been set (e.g. if a: print('a is set') else: print('a has not been set')
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With