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]
?
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With