Odd truth result with in and ==

Chris Angelico rosuav at gmail.com
Fri Nov 23 19:32:12 EST 2018


On Sat, Nov 24, 2018 at 11:28 AM John Pote <johnpote at jptechnical.co.uk> wrote:
> But the following I found unexpected. (Python 3.6 on a Windows 7 64 bit box)
>
>  >>> if []: print("Truthy")
> ...
>  >>> if [1,2,3]: print("Truthy")
> ...
> Truthy
>  >>>
>
> from which I concluded [] is Falsey and [1,2,3] is Truthy and the above
> if statements work as expected.

This is correct. Empty collections are falsey, non-empty collections are truthy.

> but,
>
>  >>> [1,2,3] == True
> False
>  >>>
>
> is unexpected as to my mind as [1,2,3] is 'Truthy' and True has ultimate
> 'Truthiness'.

This is also correct, because now you're asking if this is EQUAL TO
the specific value "True".

It is true to say that Python is a programming language.
It is true to say that a python is a snake.
It is NOT true to say that these statements are equivalent.

> Any ideas? Is there an implicit 'casting' taking place and if so is this
> documented somewhere?
>
> I interpret the above comparison as
>
>  >>> bool([1,2,3]) == bool(True)
> True
>  >>>

If you want to check if two values have the same truthiness, then this
would be how you do it. (Or you could say "not [1,2,3] == not True",
but that's a bit less clear.) An equality check is not the same. You
would not expect 4 to be equal to 5, but both of them are truthy
values (since they're both nonzero).

ChrisA



More information about the Python-list mailing list