3

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?

Matthew
  • 267
  • 1
  • 14
  • 2
  • True and False have ordinal value of 0 and 1 IIRC. Hence that behaviour. If you want to interpret as bool then use, e.g. `bool(6)` – David Heffernan Jan 15 '17 at 16:47
  • Looks to me like this was closed too hastily. 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`. – Tom Zych Jan 15 '17 at 16:55
  • Ah! Thank you Tom! I understand now. Sorry for my ignorance on this truth behaviour, now you've explained I actually feel silly for not noticing that myself in the first place. Any way to provide you with the credit due for a correct answer even though it's a comment? – Matthew Jan 15 '17 at 16:59
  • @Matthew Now that it's been reopened, yes :) – Tom Zych Jan 15 '17 at 17:00
  • Tsk, well, at least now it's linked to the right duplicate ... – Tom Zych Jan 15 '17 at 17:12

1 Answers1

2

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)
Tom Zych
  • 13,329
  • 9
  • 36
  • 53