[Tutor] Question about list

John Fouhy john at fouhy.net
Tue Apr 11 00:42:42 CEST 2006


Hi Hoffmann,

On 11/04/06, Hoffmann <oasf2004 at yahoo.com> wrote:
> 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

Have you read about "for" loops?  The pythonic way of looping through
a list is to do something like this:

for item in list1:
    print item

This will produce the same output as your code above, but is much
nicer to read :-)

> I also would like to print the length of each element
> of that list:
>
> spam! = 1 element
> 2 = 1 element
> ['Ted', 'Rock'] = 2 elements

The challenge here is that your list contains a mixture of different types.

For example, the len() function will tell us that ['Ted', 'Rock'] has
two elements.  But it would also tell us that 'spam!' has five
elements, and it would raise an exception if we tried to find the
length of 2.

So you will need to ask python about the type of element you're
looking at.  One possibility that might work for you is this:

for item in list1:
    if isinstance(item, (tuple, list)):
        print len(item)
    else:
        print 1

May I ask why you're doing this?  This feels like a situation where
you need to think clearly what your goals are before you go diving
towards a solution :-)

--
John.


More information about the Tutor mailing list