Connecting Tech Pros Worldwide Help | Site Map

Re: Testing for an empty list

Matthew Fitzgibbons
Guest
 
Posts: n/a
#1: Jul 3 '08
Alexnb wrote:
Quote:
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()

-Matt
Cameron Laird
Guest
 
Posts: n/a
#2: Jul 4 '08

re: Re: Testing for an empty list


In article <mailman.37.1215119171.20628.python-list@python.org>,
Matthew Fitzgibbons <elessar@nienna.orgwrote:
Quote:
>Alexnb wrote:
Quote:
>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()
Roy Smith
Guest
 
Posts: n/a
#3: Jul 4 '08

re: Re: Testing for an empty list


In article <luc0k5-spf.ln1@lairds.us>, claird@lairds.us (Cameron Laird)
wrote:
Quote:
In article <mailman.37.1215119171.20628.python-list@python.org>,
Matthew Fitzgibbons <elessar@nienna.orgwrote:
Quote:
Alexnb wrote:
Quote:
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.
Closed Thread