[Tutor] List exercise

Jeff Shannon jeff@ccvcorp.com
Fri Feb 7 15:40:03 2003


Larry Holish wrote:

>On Fri, Feb 07, 2003 at 08:30:42PM +0800, Anwar.Lorenzo@gmx.net wrote:
>  
>
>>As an exercise, write a loop that traverses the previous list 
>>(['spam!', 1, ['Brie', 'Roquefort', 'Pol le Veq'], [1, 2, 3]]) and 
>>prints the length of each element. What happens if you send an 
>>integer to len? (exercise from 8.3)
>>    
>>
>
>The type() builtin may also be useful for this problem:
>
>import types
>if type(mylist) == types.ListType:
>   print 'mylist is a list'
>

However, lists are not the only thing that have a length.  Strings and 
tuples also have a length, and so do some class instances.  In order to 
deal with all of those using type(), you'd have to have a series of 
if-clauses for each and every possibility... which you can't properly 
do, anyhow, because an object might be a class instance that defines its 
own __len__(), or it might be a subclass of a list, or any of a number 
of other possibilities.

One of the standard Python idioms is that it's easier to ask forgiveness 
than to ask permission.  In other words, try it but be ready to catch an 
exception.

 >>> def ExerSize():
...     exer = ['spam!', 1, ['Brie', 'Roquefort', 'Pol le Veq'], [1, 2, 3]]
...     i = 0
...     while i < len(exer):
...         try:
...             print len(exer[i])
...         except TypeError:
...             print "Item does not have a length!"
...         i = i + 1
...
 >>> ExerSize()
5
Item does not have a length!
3
3
 >>>

Note, also, that there's a better way to examine every item in a list 
than to use an explicitly incremented index variable.  The Python for 
loop takes any sequence (list, tuple, string, etc) and iterates over 
each element in that sequence.  So the previous code can be re-written 
like this:

 >>> def ExerSize():
...     exer = ['spam!', 1, ['Brie', 'Roquefort', 'Pol le Veq'], [1, 2, 3]]
...     for item in exer:
...         try:
...             print len(item)
...         except TypeError:
...             print "Item does not have a length!"
...        
 >>> ExerSize()
5
Item does not have a length!
3
3
 >>>

You get exactly the same results, and the code is less confusing and 
less likely to have odd errors (like the infinite loop due to an 
indentation error).

Jeff Shannon
Technician/Programmer
Credit International