[Tutor] Question about list

Hoffmann oasf2004 at yahoo.com
Tue Apr 11 00:52:22 CEST 2006


--- John Fouhy <john at fouhy.net> wrote:

> 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.
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 

Hi John,

This is just a version of a book exercise (How to
think like a computer scientist - learning with
python, by Downey, Elkner, and Meyers), page 84.

Thanks,
Hoffmann

__________________________________________________
Do You Yahoo!?
Tired of spam?  Yahoo! Mail has the best spam protection around 
http://mail.yahoo.com 


More information about the Tutor mailing list