Wupppa
Wupppa

Reputation: 37

How to solve TypeError: 'bool' object is not iterable in Python

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 ) 

Upvotes: 0

Views: 3329

Answers (2)

Wupppa
Wupppa

Reputation: 37

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

Upvotes: 1

Bob
Bob

Reputation: 1070

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)

Upvotes: 2

Related Questions