First of all, there is no typecasting in Python. False == 0
is true because bool
is a subclass of int
, and the two objects really are equal.
And no, there is no ===
operator, you need to explicitly test for types if you don't want this to happen:
lst = [....]
testvalue = False
if any(testvalue == elem and type(testvalue) is type(elem) for elem in lst):
# lst contains testvalue and it is the same type
This explicitly asserts that the two objects are the exact same type, disallowing for subclasses.
Yes, this is a loop. But in
for a list also uses a loop, only internally, and both the in
containment check and any()
short circuit, they return True
as soon as the first match is found.
Note that this would disallow float
equality too. 0.0 == 0
is true too, but by testing for exact types you disallow that as well. The same goes for complex numbers, and Decimal()
:
>>> 0j == 0 == 0.0 == Decimal('0')
True
bool
is just another numeric type here, albeit one limited to the numeric values 0 and 1.
The better approach, going forward, is to use type hinting in your code; the type hints checker would catch issues like you using booleans where integers or numbers are expected.