try
.. except
is certainly one way to go. If you are trying to test arguments within a function, then it is often useful to define this argument with the default value None
and test like this:
def myfunc(..., mylist=None):
if mylist is None:
mylist = []
(see also not None test in Python)
If you want to find out if the list is empty, just type
if mylist:
print mylist
else:
print "empty list"
The key difference between these types of tests and the try
.. except
concept is that in my code examples you must be sure that the variable is defined (for example as a function argument). Otherwise you will generate an Exception. And this is precisely what the try
.. except
construct handles graciously.
In the end it may be philosophical (and I can only hope that I don't violate the zen of python with this): If you know which variables may be undefined, it can improve the readability and resilience of your code if you code the error handling explicitly. Some might say it is more pythonic to "let it happen" and fix only where necessary. If you are writing a "quick hack", solution 2 is often fine, if it is an application that other users are supposed to use, I usually favour explicit error handling.