List bool value in Python

What is the best way to turn a list into a bool value? I am looking for something like:

return eval_bool(my_list) 

I have a custom container in which I implement the __nonzero__ method, which should work as follows:

 if self.my_list: return True return False 

But is it enough pythons? :) In any case, I wonder how Python interprets the value of the list in the if , because this code works differently:

 return my_list == True 

J.

+5
source share
2 answers

Just use:

 bool(my_list) 

Which evaluates it as the "truth" of Python and returns a real boolean value.

+15
source

If len(my_list) == 0 returned as false , otherwise it is true . Python is written in full:

 return len(my_list) 

which, although it is returned as an integer, evaluates to true for non-zero lengths, and false otherwise.

+1
source

All Articles