# [Tutor] Question regarding the len function of a list while using a loop

Ben Markwell benmarkwell at gmail.com
Thu Apr 14 23:51:20 CEST 2005

Yes this does make sense. Thank you

On 4/14/05, Brian van den Broek <bvande at po-box.mcgill.ca> wrote:
>
> Ben Markwell said unto the world upon 2005-04-14 08:14:
> > Could somebody explain to me why the code I used to complete this
> exercise
> > doesn't work.
> > And how do you send an integer to len?
> >
> > Thanks
> >
> > Ben
> >
> > ==================================
> >
> >
> > *As an exercise, write a loop that traverses a list and prints the
> length of
> > each element. What happens if you send an integer to len?
> >
> > *>>> foo = ['spam!', 1, ['brie', 'cheddar', 'swiss'], [1, 2, 3]]
> >
> >>>>i = 0
> >>>>while i < len(foo):
> >
> > print len(foo[i])
> > i = i+1
> >
> >
> > 5
> >
> > Traceback (most recent call last):
> > File "<pyshell#28>", line 2, in -toplevel-
> > print len(foo[i])
> > TypeError: len() of unsized object
>
> Hi Ben,
>
> Max and Alberto have already explained why you got the error message.
>
> Depending on the context in which you are doing this, the having the
> error crash the program might be what is desired. (I get that the
> context is simply an exercise, but let's pretend it is an actual
> program, written in anger :-).) Or, you might want your program to
> handle the problem more elegantly.
>
> Using the general framework Alberto suggested, here's a way to do that
> (I've also thrown some string formatting in to make the output more
> friendly):
>
> >>> foo = ['spam!', 1, ['brie', 'cheddar', 'swiss'], [1, 2, 3]]
> >>> for item in foo:
> ... try:
> ... print "Item: %s has length %s" %(item, len(item))
> ... except TypeError:
> ... print "Item: %s has no length" %item
> ...
> Item: spam! has length 5
> Item: 1 has no length
> Item: ['brie', 'cheddar', 'swiss'] has length 3
> Item: [1, 2, 3] has length 3
> >>>
>
> This works by attempting to do the thing in the try part, and catching
> any case than raises a TypeError (as your original code did), doing
> the routine of the except block instead.
>
> Does that make sense?
>
> If not, post back and I can try to explain in more detail.
>
> Best,
>
> Brian vdB
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050414/87422d4c/attachment.htm