Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

False matching with 0 in a list python [duplicate]

Tags:

python

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).

like image 812
baba26 Avatar asked Oct 26 '17 08:10

baba26


People also ask

How do you check if a number is repeated in a list Python?

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().

How do you check if values in a list are equal Python?

if len(set(input_list)) == 1: # input_list has all identical elements.

How do you compare numbers in a list Python?

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.

How do you check if an element of a list is in another list Python?

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.


1 Answers

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.

like image 107
Martijn Pieters Avatar answered Nov 08 '22 05:11

Martijn Pieters