Venkat
Venkat

Reputation: 59

Python: bool(-1) is returning true. Why does this happen?

I decided to cast -1 into a bool to check what the outcome was.

Contrary to my Expectation that bool(-1) would return False it returns True.

Why is this the case?

Upvotes: 2

Views: 2208

Answers (3)

In numbers, only 0 (after evaluation) can make False as shown below:

print(bool(0)) # False

And, None and empty string can also make False as shown below:

print(bool(None)) # False
print(bool("")) # False

And, these below can make True as shown below:

print(bool("0")) # True
print(bool("None")) # True
print(bool(" ")) # True
print(bool("False")) # True

In addition, 1 is True and 0 is False as shown below:

print(1 == True) # True
print(0 == False) # True

Upvotes: 0

Andreas
Andreas

Reputation: 2521

Based on Python 3 documentation, most of the built-in objects considered false are:

  • Constants defined to be false: None and False.
  • Zero of any numeric type: 0, 0.0, 0j, Decimal(0), Fraction(0, 1)
  • Empty sequences and collections: '', (), [], {}, set(), range(0)

Notice that it only specifies zero to be false, instead of any value that is equal to or lower than 0. This is also common in various other programming languages.

Upvotes: 5

Cortex0101
Cortex0101

Reputation: 927

TL;DR

Yes, this is expected. Most programming languages only consider 0 to be false.

Elaborated

This makes sense when you consider how -1 is represented in the processor. Typically you convert a positive number to it's negative counterpart by using 2's complement. 2's complent represents a negative binary number by inverting all the bits and adding 1. Say we have a 4-bit architecture, the decimal 1 is represented as 0001. To get its negative representation, invert all the bits and add 1, thus 0001 becomes 1110 + 1 = 1111.

When we want to know if a value is false, we can or all its inputs, if the result is 0, it's false, otherwise it's true, and thus it makes perfect sense that -1 == true.

The reson that we use 2's complement, as appose to 1's complement (where we just invert all bits without adding 1) is exacly because we do not want to be able to represent both 0 and -0.

Upvotes: 3

Related Questions