and [True,True] --> [True, True]?????

Steven D'Aprano steven at
Mon Apr 20 11:26:34 CEST 2009

On Mon, 20 Apr 2009 10:54:40 +0200, Gerhard Häring wrote:

> Peter Otten wrote:
>> bdb112 wrote:
>>> Your explanation of Boolean ops on lists was clear. It leads to some
>>> intriguing results:
>>> bool([False])
>>> --> True
>>> I wonder if python 3 changes any of this?
>> No. Tests like
>> if items:
>>    ...
>> to verify that items is a non-empty list are a widespread idiom in
>> Python. They rely on the behaviour you observe.
> Are they widespread? I haven't noticed, yet.
> I prefer to write it explicitly:
> if len(lst) > 0:

Do you also count the length of a list explicitly?

n = 0
for item in lst:
    n += 1
if n > 0:

No? Of course you don't. You understand that lists know how to calculate 
their own length, and you just ask the list for its length. Great.

Well, lists also know whether or not they are empty, without needing to 
concern yourself with the definition of "empty".

if lst:
    # not empty
    # empty

All Python objects have an understanding of "empty" or "not empty", and 
the only time I've seen it cause problems is with iterators, because you 
can't tell if an iterator is empty until you actually try to access a 

> if item is None:
>     ...

That's a completely different test. That's testing whether item is the 
specific singleton None. It is very different from testing bool(item).


More information about the Python-list mailing list