Testing for an empty list

Roy Smith roy at panix.com
Thu Jul 3 22:26:57 EDT 2008


In article <luc0k5-spf.ln1 at lairds.us>, claird at lairds.us (Cameron Laird) 
wrote:

> In article <mailman.37.1215119171.20628.python-list at python.org>,
> Matthew Fitzgibbons  <elessar at nienna.org> wrote:
> >Alexnb wrote:
> >> Okay this is a simple question I just don't know how. If I have a list, 
> >> say:
> >> 
> >> funList = []
> >> 
> >> and after a while something possible should have been appended to it, but
> >> wasn't. How can I test if that list is empty.
> >
> >if not funList:
> >	do_something()
> 			.
> 			.
> 			.
> It's also perfectly legitimate--and arguably even more 
> precise--to write
> 
>     if funList == []:
> 	do_something()

Any of these will be true for an empty list and false for a non-empty list:

    not funList
    len(funList) == 0
    funList == []

Where they differ is how they behave for values of funList which are not 
lists.  For example, if you did funList = (), then the first two would be 
true and the last one false.  If you did funList = 0, the first and last 
would be true, and the middle one would raise an exception.

The point is that if you're *sure* the item in question is going to be a 
list, then any of them are pretty much as good as any other.  If it's a 
parameter that's being passed into a routine, so you can't be sure what 
type it is, then you should be thinking a little harder about how flexible 
you want to be.



More information about the Python-list mailing list