Simple console test:
>>> if len(b) == 0: print "Ups!" ... Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'b' is not defined
>>> try: ... len(b) ... except Exception as e: ... print e ... name 'b' is not defined
Examples show how to check if a list contains items:
alist = [1,2,3] if alist: print "I'm here!" Output: I'm here!
Otherwise:
alist = [] if not alist: print "Somebody here?" Output: Somebody here?
If you need to check for the existence / non-existence of a list / tuple, maybe this can help:
from types import ListType, TupleType a_list = [1,2,3,4] a_tuple = (1,2,3,4) # for an existing/nonexisting list # "a_list" in globals() check if "a_list" is defined (not undefined :p) if "a_list" in globals() and type(a_list) is ListType: print "I'm a list, therefore I am an existing list! :)" # for an existing/nonexisting tuple if "a_tuple" in globals() and type(a_tuple) is TupleType: print "I'm a tuple, therefore I am an existing tuple! :)"
If we need to avoid in globals () , we can use this:
from types import ListType, TupleType try:
Bibliography: 8.15. types - names for built-in types - Python v2.7.3 documentation http://goo.gl/82TSr
user1630938
source share