Python array elements in if statement
Asked Answered
S

5

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

Sake answered 24/4, 2018 at 16:4 Comment(4)
please properly indent your codeAnatomy
This link might be useful to you, possible duplicate? #10063454Denumerable
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 minimal reproducible example, although your question is almost certainly a duplicateKrasnoyarsk
This isn't an array but a list with name arrayJeopardy
F
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")
Faultfinding answered 24/4, 2018 at 16:7 Comment(0)
P
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")
...
Provinciality answered 24/4, 2018 at 16:11 Comment(0)
N
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

Nuno answered 24/4, 2018 at 16:9 Comment(0)
H
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.

Hoebart answered 24/4, 2018 at 16:16 Comment(1)
I did indent it properly in my code, but sorry, not here in post.Sake
A
0

I gave this a go

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

x1 = (array[0])
x2= (array[1])
x3= (array[2])
x4= (array[3])
x5= (array[4])


if x1 <= x2:
  print("very good")
else:
  print("also good")

how's that?

Ademption answered 6/5 at 11:56 Comment(1)
As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.Disbelief

© 2022 - 2024 — McMap. All rights reserved.