0

When I am running my code I suddenly get an unexpected error: ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

I am trying to check if a tuple occurs within a list:

concat_tuples = [(7, 18), (7, [0, 10, 19]), (7, 16)]
to_explode = [c for c in concat_tuples if any(isinstance(x, list) and 
              len(x) > 1 for x in c)]
# >> to_explode = [(7, [0, 10, 19])]
not_explode = [x for x in concat_tuples if x not in to_explode]

However, my last line of code fails in my script for the first value (and probably also for the other values). The weird thing is that it works in my Python console, but not in my script (pytests). What could be going wrong in my script?

What I have tried

  • Checking existence in list with list.index(). This also fails with the same error
  • Checked types of both x and to_explode, they're a tuple and list of tuples respectively
  • Reformatted the code: list comprehension to regular for-loop, still no success
  • Run the code in Python console, which works
chatax
  • 990
  • 3
  • 17
  • I get a `NameError` saying that `concat_tuple` is not defined. Do you happen to have two unrelated variables called `concat_tuple` and `concat_tuples`? – Wander Nauta Aug 18 '21 at 10:20
  • I checked, but it was just a typo in my question – chatax Aug 18 '21 at 10:21
  • What is the associated test case that can reproduce the error? As it is now, the question cannot be answered by anyone else as they do not have access to the code that is actually failing. – metatoaster Aug 18 '21 at 10:21
  • Looks like whatever is consuming is causing the issue is not a standard `list` or `tuple` type, but rather some `numpy` array - see example [thread](https://stackoverflow.com/questions/22175489/numpy-valueerror-the-truth-value-of-an-array-with-more-than-one-element-is-ambi). – metatoaster Aug 18 '21 at 10:26
  • Which is weird, because I am print types before checking (see the what I have tried in my question) – chatax Aug 18 '21 at 10:27
  • Either way, without the code required to fully reproduce the error message, it is impossible to accurately determine what is wrong with what was posted so far (which as you noted, works). – metatoaster Aug 18 '21 at 10:33
  • It works for me and not_explode gives me [(7, 18), (7, 16)]. I tried it with jupyter notebook –  Aug 18 '21 at 10:53

1 Answers1

0

It turned out that sometimes the mostly the tuples contained integers and sometimes they contained numpy int32 objects, which caused the error. I fixed it with by casting everything to strings.

chatax
  • 990
  • 3
  • 17