Why can't I detect that the tuple is empty? Why can't I detect that the tuple is empty? numpy numpy

Why can't I detect that the tuple is empty?


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.


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