Search code examples
pythonlistif-statementtuplesvalueerror

ValueError when checking if tuple occurs in list of tuples


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

Solution

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