--- Terry Carroll <[EMAIL PROTECTED]> wrote: > On Mon, 10 Apr 2006, Hoffmann wrote: > > > Hello, > > > > I have a list: list1 = [ 'spam!', 2, ['Ted', > 'Rock'] > > ] > > and I wrote the script below: > > > > i = 0 > > while i < len(list1): > > print list1[i] > > i += 1 > > > > Ok. This script will generate as the output each > > element of the original list, one per line: > > > > spam! > > 2 > > ['Ted', 'Rock'] > > > > I also would like to print the length of each > element > > of that list: > > > > spam! = 1 element > > 2 = 1 element > > ['Ted', 'Rock'] = 2 elements > > Well, the length of "spam!" is 5. Lengths of > strings express the number > of characters. > > You could check to see if it's a grouping-type of > element -- i.e., a list, > tuple or set -- but I think your better approach is > that, if this is > something you need, make all of the elements lists, > some of which are > single-item lists; for example, instead of: > > list1 = [ 'spam!', 2, ['Ted', 'Rock'] ] > > use: > list1 = [ ['spam!'], [2], ['Ted', 'Rock'] ] > > >>> list1 = [ ['spam!'], [2], ['Ted', 'Rock'] ] > >>> for item in list1: > ... print item, len(item) > ... > ['spam!'] 1 > [2] 1 > ['Ted', 'Rock'] 2 > > If your heart is set on the other approach, though, > it can be done: > > >>> list1 = [ 'spam!', 2, ['Ted', 'Rock'] ] > >>> for item in list1: > ... if isinstance(item,(list, tuple, set)): > ... print item, len(item) > ... else: > ... print item, 1 > ... > spam! 1 > 2 1 > ['Ted', 'Rock'] 2 > >>> > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor >
Hi Terry, Your aproaches (mainly the last one!) answered my question. After following your last approach, I got what I was looking for. Up to the page I am (page 84 of "How to think like a computer scientist - learning with Python"), I didn't see that nice approach. Thanks! Hoffmann __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor