and [True,True] --> [True, True]?????

"Martin v. Löwis" martin at v.loewis.de
Mon Apr 20 16:24:41 EDT 2009


>> I don't want to test whether the length of the list
>> is greater than 0 [...] - I want to know whether the
>> list is empty (or not empty).
> 
> I fail to see the difference between "length greater than 0"
> and "list is not empty".  They are, by definition, the same
> thing, aren't they?

Yes, they test the same property, and so would

for x in foo:   # foo is empty if it does not have any elements
  # not empty
  break
else:
  # empty

People also write, as a test for empty lists,

if foo == []:     # foo is empty when it is equal to the empty list
   # empty

if foo != []:
   # not empty

Yet another equivalent test would be

try:
  foo[0]         # foo is empty if it does not have a zeroeth element
except IndexError:
  # empty
else:
  # not empty

They are *not* the same thing, by definition, as they work
in different ways. They just yield the same result.

There are many equivalent ways to spell this property; some
are more direct than others. I find that referring to the
boolean-ness of a list is the most direct way to test whether
a list is empty - just as testing for the boolean-ness of
an integer is the most direct way to test whether it is 0.

Regards,
Martin



More information about the Python-list mailing list