checking if a list is empty
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Wed May 11 07:14:25 EDT 2011
On Wed, 11 May 2011 11:48:16 +0200, Laurent Claessens wrote:
> Once I wrote something like:
>
> def f(x=None):
> if x:
> print x
> else:
> print "I have no value"
>
>
> The caller of that function was something like f(cos(2*theta)) where
> theta come from some computations.
>
> Well. When it turned out that theta was equal to pi/4, I got "I have no
> value". I spent a while to figure out the problem :)
I believe you are grossly oversimplifying whatever code you had. Using
the definition of f from above:
>>> theta = math.pi/4
>>> f(math.cos(2*theta))
6.12303176911e-17
But even if you rounded the result of cos(2*theta) to zero, you will get
the same result regardless of whether you test for "if x" or "if x != 0".
> Conclusion: the boolean value of an object is to be used with care in
> order to tests if an optional parameter is given or not (when default
> value is None).
Or, to put it another way: if you want to test for an object being None,
test for the object being None.
--
Steven
More information about the Python-list
mailing list