0

a = np.random.randint(1, 10, (3,3))
b = np.random.randint(1, 10, (3,3))
c = None

l1 = [a, b, c]

for l in l1:
  if l is None:
    l1.remove(l)
  l1

I am getting ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all(). Since it already checks if l is none then why can it not remove it ?

AMC
  • 2,642
  • 7
  • 13
  • 35
Wu Daozi
  • 51
  • 3
  • **Please provide a [mcve], as well as the entire error message.** _Since it already checks if l is none then why can it not remove it ?_ What does checking if `l` (which is explicitly mentioned as a bad name in PEP 8, by the way) is `None` have to do with the issue? – AMC Mar 20 '20 at 22:48
  • 1
    Does this answer your question? [ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()](https://stackoverflow.com/questions/10062954/valueerror-the-truth-value-of-an-array-with-more-than-one-element-is-ambiguous) – AMC Mar 20 '20 at 22:48
  • Look at `a is None` – hpaulj Mar 20 '20 at 22:53

2 Answers2

1

Basically your code does [a, b, c].remove(c) which does something like:

for x in [a, b, c]:
    if x == c:
        # remove x

The if x == c: breaks in the first case where x is a: a == None returns a new array.

That's why you get that message. Marcel's answer has the right fix. You shouldn't be modifying (with remove) a list as you iterate over it anyway.

Alex Hall
  • 34,833
  • 5
  • 57
  • 89
1

The reason for this happening is that when trying to remove l (which is None) from l1, remove(l) goes through the array and checks if each element is equal to l. As soon as it finds this element, it will remove it from the list. In doing comparisons it encounters a, and checks if a == None is true. This creates an array of booleans with whether or not each element of l is None. When you use this in an if statement, it is ambiguous whether or not it true.

Instead use

l1 = [l for l in l1 if not type(l) == type(None)]

to filter out all Nones in your list.

Marcel
  • 958
  • 1
  • 7
  • 18
  • 1
    Your new code is correct, but `l is None` doesn't create an array of booleans, it's impossible to override `is`. – Alex Hall Mar 20 '20 at 19:35