0

This is my function which throws this error

   TypeError: 'bool' object is not iterable

in line:

   if all(v == 0):

My goal is in this line to check whether all values are equal to Zero.

Here is my method:

def main():


  def checklist( thelist ):
    if len(thelist) > 2:
        for v in thelist: 
            if v < 0.0: 
                print ("One negative")
            if all(v == 0):
                print( "All zero")
            else:
                print("All good")  

alist = [0.0, 0.1, 0.3, 0.0]
checklist( alist ) 




if __name__ == '__main__':
 
# Calling main() function
    main()

What I do not understand is what am I actually checking with this line as I'm apparently not checking my list.

Edited code:

  def checklist( thelist ):
    if len(thelist) > 2:
        for v in thelist: 
            if v < 0.0: 
                print ("One negative")
        if all(vs == 0 for vs in thelist):
            print( "All zero")
        else:
            print("All good")  

alist = [0.0, -0.1, 0.3, 0.0]
checklist( alist ) 
4
  • 1
    all(vs == 0 for vs in thelist) - but do not put that into the for loop. Commented Jul 8, 2022 at 12:03
  • 1
    You are checking for v, which is an item of the list. So v==0 is a bool. Just drop the for loop. Commented Jul 8, 2022 at 12:04
  • Thank you! @luk2302 It works but I want to reach that I can check both "no value negative" and "at least one not none" before returning the else: So I modified it to the code I have edited in my question but now it prints: "One negativ" and "all good". How can I change it that it only prints "one negative" with the given list? Commented Jul 8, 2022 at 12:09
  • Maybe I did not explicitly mention my goal. I want to print "all good" if and only if all values are not negative AND at least one value is not zero. Many thanks again! Commented Jul 8, 2022 at 12:14

2 Answers 2

2

The all method expects an iterable.

In your example, v is a float and v == 0 is a boolean. So you're trying to call all for a boolean value, which isn't allowed and leads to the TypeError you're getting.

To check that all values are the 0, you can do it in the following manner:

all(v == 0 for v in alist)
Sign up to request clarification or add additional context in comments.

Comments

1
def main():


  def checklist( thelist ):
    if len(thelist) > 2:
        if all(vs == 0.0 for vs in thelist):
            print( "All zero")
        if any(v < 0.0 for v in thelist): 
            print ("At least one negative")
        else:
            print("All good")  

alist = [-1.0, 1.0, 1.0, 1.0]
checklist( alist ) 

Solved it! Thanks to @luk2302

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.