[Tutor] True and 1 [was Re: use of the newer dict types]

Steven D'Aprano steve at pearwood.info
Sun Jul 28 04:31:21 CEST 2013


On 28/07/13 05:29, Jim Mooney wrote:
> On 27 July 2013 12:14, Don Jennings <dfjennings at gmail.com> wrote:
>>
>> An empty list does evaluate to False, but a list which contains another list (even if the contained list happens to be empty) evaluates to True.

Don's explanation is mistaken. An empty list does not evaluate to False (the constant):

py> [] == False
False

Instead, an empty list behaves *like* False *in a truth-context*. And similarly for non-empty lists behaving *like* True. To try to avoid confusion, we sometimes say that [] is "false-like", or "falsey", while non-empty lists like [0, 1] are "true-like" or "truthy".

This is just duck-typing for true|false values. Any object can quack like the bool False, or like the bool True. Normally, that is all you need, but for those (rare!) cases where you want to convert a truthy value into a canonical True|False value, you can use bool:


py> bool([])
False

py> bool([0, 1])
True


What on earth is a "truth-context"? Any place that Python needs to make a Boolean yes|no, true|false, 1|0 decision:

if condition: ...
elif condition: ...

while condition: ...

x if condition else y


are the four obvious cases that spring to mind. In some languages, the condition must evaluate to an actual Boolean true|false value. Not Python, which supports duck-typing in truth-contexts. In effect, when you have a truth-context, Python automatically calls bool() on the condition for you. (Please don't learn the bad habit of manually calling bool, it is unnecessary and inefficient.)

As a general rule, Python distinguishes objects which are "something" versus "nothing":

# Objects which represent "nothing" are falsey:
0
0.0
''
None
[]
{}
any other empty container


# Objects which represent "something" are truthy:
1
2.0
'spam'
object()
non-empty lists
non-empty dicts
any other non-empty container


> Now I'm really confused, since why am I getting this? (py3.3, since I
> forgot to mention that)
>
>>>> [[]] == True
> False


A list containing anything, or nothing at all, is not equal to the constant True. This is probably what you wanted to test:

py> bool([[]])
True



-- 
Steven


More information about the Tutor mailing list