5

I have some array with integers, and for loop. I am trying to test if some specific elements in array is bigger or smaller that some integer. This code explain it better:

array = [1,2,3,4,5]
for i in range(5):
    if array[i] >= 3:
        print(sometext)
    else:
        print(othertext)

But i got an ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

SOLUTION: I did indent it properly. This above is just simplification(some stupid example) of my code. I found where the error is. It is because I initialized array with numpy as

a = numpy.empty(5) and not like this:

a = [0 for i in range(5)]

Thank you everybody for your help

Falco Peregrinus
  • 507
  • 2
  • 7
  • 19
  • 2
    please properly indent your code – Joe Iddon Apr 24 '18 at 16:06
  • This link might be useful to you, possible duplicate? https://stackoverflow.com/questions/10062954/valueerror-the-truth-value-of-an-array-with-more-than-one-element-is-ambiguous – Wool Apr 24 '18 at 16:07
  • 4
    This might seem pedantic, but that isn't an array, that is a `list`. However, your error message seems to come from `numpy`. You should provide a [mcve], although your question is almost certainly a duplicate – juanpa.arrivillaga Apr 24 '18 at 16:07
  • 3
    This isn't an array but a list with name array – Vicrobot Apr 24 '18 at 16:08

4 Answers4

4

You should iterate over the array itself:

array = [1, 2, 3, 4, 5]

for item in array:
    if item >= 3:
        print("yes")
    else:
        print("no")
Gabriel
  • 1,922
  • 2
  • 19
  • 37
2

It worked for me with proper intendations:

>>> array = [1,2,3,4,5]
>>> for i in range(5):
...     if array[i] >= 3:
...             print("Yes")
...     else:
...             print("No")
...
Anand.G.T
  • 61
  • 6
0

This isn't really the most pythoninc way of doing what you're describing.

array = [1,2,3,4,5]
for element in array:
    if element >= 3:
        print("Yes")
    else:
        print("No")

Reference: https://wiki.python.org/moin/ForLoop

tbobm
  • 113
  • 1
  • 9
0

The Error that you are getting is basically due to INDENTATION . Python strictly follows indentation , meaning that it will only execute codes written in that specific Block . Refer Python Indentation Rule for more details. Thank You. Happy Coding Ahead.

Chandra Shekhar
  • 598
  • 1
  • 7
  • 25