Thanks,
Srini
Add more friends to your messenger and enjoy! Go to http://messenger.yahoo.com/invite/
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
"if not A"
-tkc
Empty collections are "false":
if somelist:
... # somelist isn't empty
else:
... # somelist is empty
Bye,
bearophile
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
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
>
>
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
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.
PEP 8 recommends the latter.
Raymond
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
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
>
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
it's the next-to-last sub-item, just before the references.
http://www.python.org/dev/peps/pep-0008/
andrew
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
--
mph
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
>>>
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
Yes, but notice that one of them goes wrong by raising an exception,
whereas the other goes wrong by failing silently.
Carl Banks
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
Connect with friends all over the world. Get Yahoo! India Messenger at http://in.messenger.yahoo.com/?wm=n/
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
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/
> 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
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
> 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!