Search code examples
pythonpython-3.xbooleanshort-circuiting

Python all([6,7,8,9]) = True. But 6 = False


My understanding of the all() operator is that it returns true if all elements of an iterable return a value of true. Either I'm misunderstanding it's function completely, or something isn't quite right in the following:

>>> all([0, 7, 8, 9])
False
>>> all([6, 7, 8, 9])
True
>>> any([0, 7, 8, 9])
True
>>> 0 == True
False
>>> 1 == True
True
>>> 6 == True
False
>>> 7 == True
False

What's up with this?

Edit Okay, I'm getting a lot of answers explaining that 0 is false. I get that. 0 = False and 1 = True. My issue is that 6 is returned as False, yet when tested as part of a list it returns as true?

>>> all([6, 7, 8, 9])
True
>>> 6 == True
False

This is the bit I don't get?


Solution

  • Check me: what you’re really asking is, 6 and 7 appear to be False, so why is the second expression True. If so, the answer is that nonzero integers evaluate to True in a boolean context; but when you test 6 == True, the integer is not being coerced into a boolean type, so effectively you’re testing 6 == 1, which is False.

    Edit: The correct way to test if something is True in a boolean context is, for example:

    bool(6)