checking if a list is empty

Roy Smith roy at panix.com
Wed May 11 08:26:53 EDT 2011


Hans Georg Schaathun <hg at schaathun.net> wrote:

> li == [] is as explicit as it gets, and
> leaves no room for doubt.

I was about to write, "this fails if li is an instance of a subclass of 
list", but then I tried it.  I was astounded to discover that:

class MyList(list):
    "I'm a subclass"

li = MyList()
print li == []
print [] == li

prints True, twice!  I expected them both to be false.  In fact, the 
docs (http://tinyurl.com/3qga3lb) explicitly say:

> If both are numbers, they are converted to a common type. Otherwise, 
> objects of different types always compare unequal

Since these are different types, i.e.

print type(li)
print type([])
print type(li) == type([])

prints

<class '__main__.MyList'>
<type 'list'>
False

I conclude that li == [] should have returned False.  Either I'm not 
understanding things correctly, or this is a bug.



More information about the Python-list mailing list