On May 6, 2011, at 5:57 PM, scattered wrote: > On May 6, 2:36 am, Jabba Laci <jabba.l...@gmail.com> wrote: >> Hi, >> >> If I want to check if a list is empty, which is the more pythonic way? >> >> li = [] >> >> (1) if len(li) == 0: >> ... >> or >> (2) if not li: >> ... >> >> Thanks, >> >> Laszlo > > is there any problem with > > (3) if li == []: > > ?
What if it's not a list but a tuple or a numpy array? Often I just want to iterate through an element's items and I don't care if it's a list, set, etc. For instance, given this function definition -- def print_items(an_iterable): if not an_iterable: print "The iterable is empty" else: for item in an_iterable: print item I get the output I want with all of these calls: print_items( list() ) print_items( tuple() ) print_items( set() ) print_items( numpy.array([]) ) Given this slightly different definition, only the first call gives me the output I expect: def print_items(an_iterable): if an_iterable == []: print "The iterable is empty" else: for item in an_iterable: print item I find I use the the former style ("if not an_iterable") almost exclusively. bye Philip -- http://mail.python.org/mailman/listinfo/python-list