this line evaluates to True in python
False in [0,1,2]
because False
and 0
are equal after typecasting.
Is there any way to avoid this typecasting?
Something like ===
operator for list?
(I know that I can handle this case with a loop by explicitly checking for value types, but I am curious if there is some short and sweet trick to do this without a loop).
Using Count() The python list method count() returns count of how many times an element occurs in list. So if we have the same element repeated in the list then the length of the list using len() will be same as the number of times the element is present in the list using the count().
if len(set(input_list)) == 1: # input_list has all identical elements.
sort() and == operator. The list. sort() method sorts the two lists and the == operator compares the two lists item by item which means they have equal data items at equal positions. This checks if the list contains equal data item values but it does not take into account the order of elements in the list.
count() to check if the list contains. Another built-in method in Python, count() returns the number of times the passed element occurs in the list. If the element is not there in the list then the count() will return 0.
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.
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