Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check whether the numpy array exists already or not?

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.

like image 574
E H Avatar asked Feb 21 '16 20:02

E H


People also ask

How do I check if an array is NumPy?

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“.

What is __ Array_interface __?

__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.


1 Answers

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'))

like image 108
Alexander Avatar answered Sep 20 '22 13:09

Alexander