Question

I am using the where function in numpy to look for a one letter string in an array of strings. For example: I will look for 'U' in ['B' 'U' 'A' 'M' 'R' 'O'] and get the index of 'U'.

letter = 'U'
row = ['B', 'U', 'A', 'M', 'R', 'O']
letter_found = np.where(row == letter)

However when I am looking for a letter that isn't present in the array of strings I get an empty tuple that looks like this:

(array([], dtype=int64),)

I need to be able to detect when it does not find the letter I am looking for in the array.

I've tried the following:

if not letter_found:
    print 'not found'

But this does not work. How can I detect that the tuple returned from the where function in numpy is empty? Is it because one of my variables is possibly the wrong type? I am new at python and programming in general.

Was it helpful?

Solution

The nomeclature:

if some_iterable:
    #only if non-empty

only works when something is empty. In your case, the tuple isn't actually empty. The thing the tuple contains is empty. So you might want to do the following:

if any(map(len, my_tuple)):
    #passes if any of the contained items are not empty

as len on an empty iterable will yield 0 and thus will be converted to False.

OTHER TIPS

Your test is failing because letter_found is actually a tuple containing one element, so it's not empty. numpy.where returns a tuple of index values, one for each dimension in the array that you're testing. Typically when using this for searching in one-dimensional arrays, I use Python's tuple unpacking to avoid just this sort of situation:

letter = 'U'
row = ['B', 'U', 'A', 'M', 'R', 'O']
letter_found, = np.where(row == letter)

Note the comma after letter_found. This will unpack the result from numpy.where and assign letter_found to be the first element of that tuple.

Note also that letter_found will now refer to a numpy array, which cannot be used in a boolean context. You'll have to do something like:

if len(letter_found) == 0:
    print('not found!')
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top