Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Differentiate False and 0

Tags:

python

Let's say I have a list with different values, like this:

[1,2,3,'b', None, False, True, 7.0]

I want to iterate over it and check that every element is not in list of some forbidden values. For example, this list is [0,0.0].

When I check if False in [0,0.0] I get True. I understand that python casts False to 0 here - but how I can avoid it and make this check right - that False value is not in [0,0.0]?

like image 747
Paul Avatar asked Nov 16 '16 19:11

Paul


People also ask

Does 0 equal False in python?

Python assigns boolean values to values of other types. For numerical types like integers and floating-points, zero values are false and non-zero values are true. For strings, empty strings are false and non-empty strings are true.

Is 0.0 True or false?

Zero is used to represent false, and One is used to represent true. For interpretation, Zero is interpreted as false and anything non-zero is interpreted as true. To make life easier, C Programmers typically define the terms "true" and "false" to have values 1 and 0 respectively.


2 Answers

To tell the difference between False and 0 you may use is to compare them. False is a singleton value and always refers to the same object. To compare all the items in a list to make sure they are not False, try:

all(x is not False for x in a_list)

BTW, Python doesn't cast anything here: Booleans are a subclass of integers, and False is literally equal to 0, no conversion required.

like image 116
kindall Avatar answered Sep 20 '22 20:09

kindall


You would want to use is instead of == when comparing.

y = 0
print y == False # True
print y is False # False

x = False
print x == False # True
print x is False # True
like image 21
Michael Goodwin Avatar answered Sep 17 '22 20:09

Michael Goodwin