checking if a list is empty

Ian Kelly ian.g.kelly at gmail.com
Fri May 6 19:51:44 EDT 2011


On Fri, May 6, 2011 at 4:21 PM, Philip Semanchuk <philip 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())



More information about the Python-list mailing list