-3

I just learned the story behind python and boolean values representing 'int' values. So when I use the isinstance() I was expecting to receive True // False but this is what returned:

i = 3
x = 0
print(isinstance(i, bool))  <-- expecting True
print(isinstance(x, bool))  <-- expecting False

# what returned
False
False

can someone explain why? and then explain how it works in this function:

def move_zeros(arr):
l = [i for i in arr if isinstance(i, bool) or i!=0]
return l+[0]*(len(arr)-len(l))
CoderCode
  • 1
  • 4
  • Just because a cat has stripes doesn't make it a tabby. Same logic here: code inside `if 3:` runs, but that doesn't make `3` a bool value. Even `1` isn't a bool value, even though it's *numerically equal to* `True`. – Karl Knechtel Jan 14 '22 at 08:04

1 Answers1

1

bool happens to be a subclass of int, so this is true:

isinstance(True, int)

But int is not a subclass of bool, so numbers are not instances of booleans.

Even if they were, the result would be expected to be the same for both 3 and 0, as they're both instances of the same type, and their value is irrelevant for an isinstance check.


True and False are "special cases" of the numbers 1 and 0, if you will. bool is a narrow subset of int, using only two possible integers. The other way around thus makes little sense; you can't express all possible integers with just the values True and False*.

* No, bits are something else…


Subclasses work this way:

>>> class Foo:
...     pass
... 
>>> class Bar(Foo):
...     pass
... 
>>> isinstance(Foo(), Foo)
True
>>> isinstance(Bar(), Foo)
True
>>> isinstance(Foo(), Bar)
False

Bar is a subclass of Foo and thus any Bar instance is—by inheritence—also a valid instance of Foo. Not the other way around.

deceze
  • 510,633
  • 85
  • 743
  • 889
  • Understood. if you can though can you explain this code: – CoderCode Jan 14 '22 at 07:41
  • I apologize, I meant the piece of code I just added to the original question. – CoderCode Jan 14 '22 at 07:44
  • 1
    What's the input and output of that code and what don't you understand about it? – deceze Jan 14 '22 at 07:45
  • The goal of the code is to return the 'array' with all zeros at the end of the list. The piece I don't understand is: Why does the individual use the isinstance(i, bool) when, as you stated above, all numbers would return False (the array is numbers only). it seems more efficient to just use the i!=0 would you agree or am I missing something? – CoderCode Jan 14 '22 at 07:54
  • 1
    Well, if the input contained `False` values, those would be regarded as `0` and moved (and turned into `0`). Apparently the author wanted to guard against that and treat all bools as non-zero. – deceze Jan 14 '22 at 08:01
  • In general, if you want to understand why code was written a certain way, you should *ask the person who wrote it*. – Karl Knechtel Jan 14 '22 at 08:05