On May 7, 12:51 am, Ian Kelly <ian.g.ke...@gmail.com> wrote: > On Fri, May 6, 2011 at 4:21 PM, Philip Semanchuk <phi...@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. Jon Jon. -- http://mail.python.org/mailman/listinfo/python-list