[Tutor] List exercise

Michael Janssen Janssen@rz.uni-frankfurt.de
Fri Feb 7 09:27:01 2003


On Fri, 7 Feb 2003 Anwar.Lorenzo@gmx.net wrote:

> I've tried indenting that line (i = i + 1) but I got this error:
> Traceback (most recent call last):
>   File "<pyshell#2>", line 1, in ?
>     exerSize()
>   File "<pyshell#1>", line 5, in exerSize
>     len(exer[i])
> TypeError: len() of unsized object
>
now, variable i is incrementing and therefore exer[i] returns it's items
from index position 0 till last index of exer.

But at least one of this items is an object which isn't sized (as the
traceback mentions): this means it's forbidden to run len() about. For
Example: integer 10 is unsized, since it doesn't make sence to speak of
the length of an integer.

To find out, which item is of an unsized type, you could do:

1.) Print every item before run len() over it. Last printed item before
traceback is the critical one.
while i < len(exer):
     print exer[i]
     len(exer)

2.) Enhance this:
while i < len(exer):
     print i, type(exer[i]), exer[i] # gives you more informations
     len(exer)

3.) Catch the exception, and print information only for the critical
item.
while i < len(exer):
     try:
          len(exer)
     except TypeError:
          print i,type(exer[i]),exer[i]

4.) You can - of course - look through your code and find out what type of
object did you actually stick into exer. You will find, that you've got an
integer in your example code.

In the case you want to have a list "exer" with sized an unsized types
mixed and also want to get the length of each list-item, you need to put
solution 3. into your code and provide a sensible method to handle unsized
objects: you can "pass" them or do len(str(exer[i])) or anything else you
find suitable.

Michael

> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>