checking if a list is empty

Hans Mulder hansmu at xs4all.nl
Sat May 14 04:52:50 EDT 2011


On 07/05/2011 02:43, Jon Clements wrote:
> On May 7, 12:51 am, Ian Kelly<ian.g.ke... at gmail.com>  wrote:
>> On Fri, May 6, 2011 at 4:21 PM, Philip Semanchuk<phi... at semanchuk.com>  wrote:
>>> 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([]) )
>>
>> But sadly it fails on iterators:
>> print_items(xrange(0))
>> print_items(-x for x in [])
>> print_items({}.iteritems())
>
> My stab:
>
> from itertools import chain
>
> def print_it(iterable):
>      it = iter(iterable)
>      try:
>          head = next(it)
>      except StopIteration:
>          print 'Empty'
>          return
>      for el in chain( (head,), it ):
>          print el
>
> Not sure if I'm truly happy with that though.

How about:

def print_items(an_iterable):
     found_item = False
     for item in an_iterable:
         print item
         found_item = True
     if not found_item:
         print "The iterable was empty"

-- HansM



More information about the Python-list mailing list