Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

What way is the best to check an empty list?

3 views
Skip to first unread message

srinivasan srinivas

unread,
Mar 25, 2009, 10:38:53 AM3/25/09
to pytho...@python.org

For ex: to check list 'A' is empty or not..
if A == []:
if A.count == 0:
if len(A) == 0:
if not A:

Thanks,
Srini


Add more friends to your messenger and enjoy! Go to http://messenger.yahoo.com/invite/

Andre Engels

unread,
Mar 25, 2009, 10:49:14 AM3/25/09
to srinivasan srinivas, pytho...@python.org
On Wed, Mar 25, 2009 at 3:38 PM, srinivasan srinivas
<sri_a...@yahoo.co.in> wrote:
>
> For ex: to check list 'A' is empty or not..
> if A == []:
> if A.count == 0:
> if len(A) == 0:
> if not A:

I would go for the last one, because it has the highest likelihood of
doing what is intended when fed with something that is 'list-like'
rather than a list. The second one is incorrect, by the way. A.count
is something completely different.

--
André Engels, andre...@gmail.com

Tim Chase

unread,
Mar 25, 2009, 10:52:18 AM3/25/09
to srinivasan srinivas, pytho...@python.org
srinivasan srinivas wrote:
> For ex: to check list 'A' is empty or not..
> if A == []:
> if A.count == 0:
> if len(A) == 0:
> if not A:

"if not A"

-tkc

bearoph...@lycos.com

unread,
Mar 25, 2009, 10:52:52 AM3/25/09
to
srinivasan srinivas:

> For ex: to check list 'A' is empty or not..

Empty collections are "false":

if somelist:
... # somelist isn't empty
else:
... # somelist is empty

Bye,
bearophile

John Machin

unread,
Mar 25, 2009, 10:55:10 AM3/25/09
to
On Mar 26, 1:38 am, srinivasan srinivas <sri_anna...@yahoo.co.in>
wrote:

Depends on what you mean by "best"; like graduation day at
kindergarten, everyone gets a prize:

> For ex: to check list 'A' is empty or not..
> if A == []:

most obviously correct

> if A.count == 0:

best use of imagination

> if len(A) == 0:

best use of a built-in function

> if not A:

most Pythonic, most laconic, fastest

andrew cooke

unread,
Mar 25, 2009, 11:21:34 AM3/25/09
to srinivasan srinivas, pytho...@python.org

i will go against the grain slightly and say that "len" is probably the
best compromise in most situations (although i admit i don't know what
count is) because i think it will work when you expect it to and break
when you have a bug in your program.

using a simple boolean is more robust (and what i typically do in my own
code because i am often too lazy to think carefully), but if it is given
something that is not "list-like" you won't get an error until later in
your code (and typically the sooner an error is found, the better).

but i may be wrong - are there any containers (apart from pathological
hand-crafted examples) that would not define __len__()?

andrew


srinivasan srinivas wrote:
>
> For ex: to check list 'A' is empty or not..
> if A == []:

> if A.count == 0:
> if len(A) == 0:
> if not A:
>

> Thanks,
> Srini
>
>
> Add more friends to your messenger and enjoy! Go to
> http://messenger.yahoo.com/invite/

> --
> http://mail.python.org/mailman/listinfo/python-list
>
>


Andre Engels

unread,
Mar 25, 2009, 11:27:50 AM3/25/09
to andrew cooke, pytho...@python.org
On Wed, Mar 25, 2009 at 4:21 PM, andrew cooke <and...@acooke.org> wrote:
>
> i will go against the grain slightly and say that "len" is probably the
> best compromise in most situations (although i admit i don't know what
> count is) because i think it will work when you expect it to and break
> when you have a bug in your program.
>
> using a simple boolean is more robust (and what i typically do in my own
> code because i am often too lazy to think carefully), but if it is given
> something that is not "list-like" you won't get an error until later in
> your code (and typically the sooner an error is found, the better).
>
> but i may be wrong - are there any containers (apart from pathological
> hand-crafted examples) that would not define __len__()?

When writing my answer, I thought of generators, but I now find that
those will have boolean value 'true' whether or not they have
something to generate, so they will go wrong under either method. The
same holds for iterators. So for now I can't find any good example.


--
André Engels, andre...@gmail.com

John Machin

unread,
Mar 25, 2009, 11:29:58 AM3/25/09
to
On Mar 26, 2:21 am, "andrew cooke" <and...@acooke.org> wrote:
> i will go against the grain slightly and say that "len" is probably the
> best compromise in most situations (although i admit i don't know what
> count is) because i think it will work when you expect it to and break
> when you have a bug in your program.
>
> using a simple boolean is more robust (and what i typically do in my own
> code because i am often too lazy to think carefully), but if it is given
> something that is not "list-like" you won't get an error until later in
> your code (and typically the sooner an error is found, the better).

When you are doing something like
if A and A[-1] == 'yadda':
you won't have to wait long for the exception if A is not
subscriptable :-)

> but i may be wrong - are there any containers (apart from pathological
> hand-crafted examples) that would not define __len__()?

Very unlikely.


Raymond Hettinger

unread,
Mar 25, 2009, 3:58:11 PM3/25/09
to
On Mar 25, 7:38 am, srinivasan srinivas <sri_anna...@yahoo.co.in>
wrote:

> For ex: to check list 'A' is empty or not..
> if A == []:
> if A.count == 0:
> if len(A) == 0:
> if not A:

PEP 8 recommends the latter.


Raymond

andrew cooke

unread,
Mar 25, 2009, 4:19:56 PM3/25/09
to Andre Engels, pytho...@python.org
Andre Engels wrote:

> On Wed, Mar 25, 2009 at 4:21 PM, andrew cooke <and...@acooke.org> wrote:
>> i will go against the grain slightly and say that "len" is probably the
>> best compromise in most situations (although i admit i don't know what
[...]

>> but i may be wrong - are there any containers (apart from pathological
>> hand-crafted examples) that would not define __len__()?
> When writing my answer, I thought of generators, but I now find that
> those will have boolean value 'true' whether or not they have
> something to generate, so they will go wrong under either method. The
> same holds for iterators. So for now I can't find any good example.


actually, the implication of what you said is probably worth emphasising
to the original poster: often you don't need to test whether a list is
empty or not, you simply iterate over its contents:

for x in foo:
# do something

this will then work with lists, tuples, sets, but also with iterators and
generators (which would give incorrect results in a test). in all cases,
"do something" will not happen if there are no data to process.

andrew


Stef Mientki

unread,
Mar 25, 2009, 4:29:45 PM3/25/09
to pytho...@python.org
Now it would be nice to allow iteration over others too, like None .
a = None
for item in a :
do_something_with_item

I created a Null object for that, but that gives all kind of problems
with i.e. configobj.

cheers,
Stef
> andrew
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>

Martin P. Hellwig

unread,
Mar 25, 2009, 5:26:10 PM3/25/09
to
I can't seem to find where this recommendation is mentioned or implied.

Personally I would go for the len version for the sole reason that its
immediate clear what it is what I am trying to do here. So that when I
reread my code a couple of weeks later I don't have to think, eh was A a
bool, oh no I was checking if that list had content in it.

But that could be just me though :-)

YMMV
--
mph

andrew cooke

unread,
Mar 25, 2009, 5:48:07 PM3/25/09
to Martin P. Hellwig, pytho...@python.org
Martin P. Hellwig wrote:
> Raymond Hettinger wrote:
>> On Mar 25, 7:38 am, srinivasan srinivas <sri_anna...@yahoo.co.in>
>> wrote:
>>> if not A:
>> PEP 8 recommends the latter.
> I can't seem to find where this recommendation is mentioned or implied.

it's the next-to-last sub-item, just before the references.
http://www.python.org/dev/peps/pep-0008/

andrew

Albert Hopkins

unread,
Mar 25, 2009, 7:04:30 PM3/25/09
to pytho...@python.org
On Wed, 2009-03-25 at 21:26 +0000, Martin P. Hellwig wrote:
> >
> > PEP 8 recommends the latter.
> >
> >
> > Raymond
> I can't seem to find where this recommendation is mentioned or implied.

Wow, you must not have looked very hard:

1. Point your browser to http://www.python.org/dev/peps/pep-0008/
2. Go to Edit->Find
3. Type "empty"
4. It's the very first (in fact only) match

-a


Martin P. Hellwig

unread,
Mar 25, 2009, 7:19:23 PM3/25/09
to
I stand corrected.

--
mph

Michiel Overtoom

unread,
Mar 25, 2009, 7:19:47 PM3/25/09
to pytho...@python.org

On 25 Mar 2009, at 21:29 , Stef Mientki wrote:

> Now it would be nice to allow iteration over others too, like None .
> a = None
> for item in a :
> do_something_with_item
>

I saw this technique used in CherryPy:

>>> a=None
>>> for item in a or []:
... print item
...
>>> a=[1,2,3]
>>> for item in a or []:
... print item
...
1
2
3
>>>

Carl Banks

unread,
Mar 25, 2009, 7:24:47 PM3/25/09
to
On Mar 25, 1:19 pm, "andrew cooke" <and...@acooke.org> wrote:
> actually, the implication of what you said is probably worth emphasising
> to the original poster: often you don't need to test whether a list is
> empty or not, you simply iterate over its contents:
>
>   for x in foo:
>     # do something
>
> this will then work with lists, tuples, sets, but also with iterators and
> generators (which would give incorrect results in a test).  in all cases,
> "do something" will not happen if there are no data to process.


Which is fine as long as you don't need to do something else in the
case of no items. But in that case you have no choice but to iterate
and see if any items are produced. There are some iterables for which
no if-test at all works.


Carl Banks

Carl Banks

unread,
Mar 25, 2009, 7:34:32 PM3/25/09
to
On Mar 25, 8:27 am, Andre Engels <andreeng...@gmail.com> wrote:
> On Wed, Mar 25, 2009 at 4:21 PM, andrew cooke <and...@acooke.org> wrote:
>
> > but i may be wrong - are there any containers (apart from pathological
> > hand-crafted examples) that would not define __len__()?
>
> When writing my answer, I thought of generators, but I now find that
> those will have boolean value 'true' whether or not they have
> something to generate, so they will go wrong under either method.

Yes, but notice that one of them goes wrong by raising an exception,
whereas the other goes wrong by failing silently.


Carl Banks

Carl Banks

unread,
Mar 25, 2009, 7:43:16 PM3/25/09
to
On Mar 25, 7:38 am, srinivasan srinivas <sri_anna...@yahoo.co.in>
wrote:
> For ex: to check list 'A' is empty or not..
> if A == []:
> if A.count == 0:
> if len(A) == 0:
> if not A:

PEP 8 recommends the last one, and most Pythonistas here probably
would as well, so that is probably what you should do if you don't
otherwise have an opinion. I have an opinion, so I use "len(A) == 0"
in projects I control.

However, if this object is intended to be an list of numbers, and if
the application does any sort of mathematical calculations, then I
recommend you use the "len(A) == 0" test and no other. This is to
allow interaction with numpy, which doesn't work with the "if not A"
test.


Carl Banks

srinivasan srinivas

unread,
Mar 25, 2009, 10:26:22 AM3/25/09
to pytho...@python.org

For ex: to check list 'A' is empty or not..
if A == []:
if A.count == 0:
if len(A) == 0:
if not A:


Connect with friends all over the world. Get Yahoo! India Messenger at http://in.messenger.yahoo.com/?wm=n/

Josh Dukes

unread,
Mar 25, 2009, 9:52:59 PM3/25/09
to pytho...@python.org
I believe "if not A:" is the most pythonic, but depending on what
you're doing a list might not be the right thing to use at all. A
little while ago I got some help from this malining list in dealing
with a situation where lists really were not efficient (finding prime
numbers...for fun). In my case the ultimate conclusion was to run any
over a generator. In my case this worked wonderfully, but there are many
cases where this would not. If you only need to know if the list is
empty, and don't care what's in it, then such an approach might work
for you.

On Wed, 25 Mar 2009 20:08:53 +0530 (IST)
srinivasan srinivas <sri_a...@yahoo.co.in> wrote:

>
> For ex: to check list 'A' is empty or not..
> if A == []:
> if A.count == 0:
> if len(A) == 0:
> if not A:
>

> Thanks,
> Srini
>
>
> Add more friends to your messenger and enjoy! Go to
> http://messenger.yahoo.com/invite/ --
> http://mail.python.org/mailman/listinfo/python-list


--

Josh Dukes
MicroVu IT Department

Steve Holden

unread,
Mar 25, 2009, 11:31:05 PM3/25/09
to pytho...@python.org
Stef Mientki wrote:
> andrew cooke wrote:
>> Andre Engels wrote:
>>
>>> On Wed, Mar 25, 2009 at 4:21 PM, andrew cooke <and...@acooke.org> wrote:
>>>
>>>> i will go against the grain slightly and say that "len" is probably the
>>>> best compromise in most situations (although i admit i don't know what
>>>>
>> [...]
>>
>>>> but i may be wrong - are there any containers (apart from pathological
>>>> hand-crafted examples) that would not define __len__()?
>>>>
>>> When writing my answer, I thought of generators, but I now find that
>>> those will have boolean value 'true' whether or not they have
>>> something to generate, so they will go wrong under either method. The
>>> same holds for iterators. So for now I can't find any good example.
>>>
>>
>>
>> actually, the implication of what you said is probably worth emphasising
>> to the original poster: often you don't need to test whether a list is
>> empty or not, you simply iterate over its contents:
>>
>> for x in foo:
>> # do something
>>
>> this will then work with lists, tuples, sets, but also with iterators and
>> generators (which would give incorrect results in a test). in all cases,
>> "do something" will not happen if there are no data to process.
>>
> Now it would be nice to allow iteration over others too, like None .
> a = None
> for item in a :
> do_something_with_item
>
To me that makes about as much sense as writing

for x in 1.0:
print x

and expecting it to print 1.0. Numbers just aren't iterable. Neither is
None. A TypeError exception is the only appropriate response.

regards
Steve
--
Steve Holden +1 571 484 6266 +1 800 494 3119
Holden Web LLC http://www.holdenweb.com/
Want to know? Come to PyCon - soon! http://us.pycon.org/

Steven D'Aprano

unread,
Mar 26, 2009, 12:27:30 AM3/26/09
to
On Wed, 25 Mar 2009 21:26:10 +0000, Martin P. Hellwig wrote:

> Raymond Hettinger wrote:
>> On Mar 25, 7:38 am, srinivasan srinivas <sri_anna...@yahoo.co.in>
>> wrote:
>>> For ex: to check list 'A' is empty or not.. if A == []:
>>> if A.count == 0:
>>> if len(A) == 0:
>>> if not A:

...

> Personally I would go for the len version for the sole reason that its
> immediate clear what it is what I am trying to do here. So that when I
> reread my code a couple of weeks later I don't have to think, eh was A a
> bool, oh no I was checking if that list had content in it.

That's not the Pythonic way. If I see code saying "if len(A) == 0", my
first thought is "Why do I care what the length is? I don't use it
anywhere else."

In my opinion, explicitly testing for the length of a list being equal to
zero makes about as much sense as testing whether an int is non-zero by
explicitly counting the on-bits. Sure, you can argue that for every non-
zero integer, there must be *at least one* on-bit, but why do you care?
Just ask the int if it's zero.

Likewise, why do you care that the list has length zero? Just ask the
list if it's empty, and the way to do that is just to refer to the list.

In Python, by design, every object can be considered as having a truth
context. "not x" should be meaningful for any object[1]. The truth
context is best thought of as "is this object something or nothing?".
Empty sequences and mappings are nothing, as are None and zero:

[] => nothing
{} => nothing
'' => nothing
None => nothing
0.0 => nothing

Most nearly everything else is something:

[1, 2, 3] => something
{1: 2} => something
"hello world" => something
5 => something


Once you understand that, you have no reason to ever be confused by a
line like "if x" again: if x is something, do this.

This works beautifully with short-circuit operators:

for x in (y or z):
do_something_with(x)

instead of:

if len(y) != 0:
tmp = y
elif len(z) != 0:
tmp = z
else:
tmp = []
if tmp:
for x in tmp:
do_something_with(x)


Being an old Pascal programmer, I can't tell you what a relief it is to
have Python's truth-testing model!

[1] Apart from pathologically weird classes like this:

class SomethingOnTuesdays(object):
def __nonzero__(self):
return time.strftime('%A') == 'Tuesday'


--
Steven

Niklas Norrthon

unread,
Mar 26, 2009, 3:18:45 AM3/26/09
to
On 26 Mar, 04:31, Steve Holden <st...@holdenweb.com> wrote:

> Stef Mientki wrote:
>
> > Now it would be nice to allow iteration over others too, like None .
> >    a = None
> >    for item in a :
> >          do_something_with_item
>
> To me that makes about as much sense as writing
>
>     for x in 1.0:
>         print x
>
> and expecting it to print 1.0. Numbers just aren't iterable. Neither is
> None. A TypeError exception is the only appropriate response.
>
I can see a use case for the latter:

def some_function(arg, coll=None):
do_stuff(arg)
for item in coll:
do_more(arg, item)

But that can easily be achieved with the "or" operator as Michiel
Overton notes elsewhere in this thread:

def some_function(arg, coll=None):
do_stuff(arg)
for item in coll or []: # <= Here or is used to make None behave
as an empty collection
do_more(arg, item)

/Niklas Norrthon

Niklas Norrthon

unread,
Mar 26, 2009, 3:27:54 AM3/26/09
to
On 26 Mar, 08:18, Niklas Norrthon <niklas.norrt...@hotmail.com> wrote:

> But that can easily be achieved with the "or" operator as Michiel
> Overton notes elsewhere in this thread:

Michiel Overtoom was what I meant to write. My apologies!

0 new messages