Tim Chase wrote: >> **************************************************************** >> a = ['spam!', 1, ['Brie', 'Roquefort', 'Pol le Veq'], [1, 2, 3]] >> >> As an exercise, write a loop that traverses the previous list and >> prints the length of each element. What happens if you send an >> integer to len? >> **************************************************************** >> >> for i in a: >> print len(a[i]) >> >> will not do. >> the list has str, int, list, list. >> I am expecting the output to be 1, 1, 3, 3 which are the number of >> elements of each element of a, someone might think the result should >> be 4, 3, 3 which is len(a), len(a[2]), len(a[3]) but how can I do both >> thoughts with a loop? > > > Well, first off, you've got a strange indexing going on there: a[i] > requires that the index be an integer. You likely *mean* > > for thing in a: > print len(thing) > > If so, you can just wrap it in a check: > > for thing in a: > if "__len__" in dir(thing):
I think the one and only one way to express this is if hasattr(thing, "__len__"): -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ -- http://mail.python.org/mailman/listinfo/python-list