[Tutor] List exercise

antonmuhin at rambler.ru antonmuhin at rambler.ru" <antonmuhin@rambler.ru
Fri Feb 7 17:03:02 2003


Hello Anwar,

Friday, February 7, 2003, 3:30:42 PM, you wrote:

ALgn> Hi
ALgn> I'm trying to solve the exercise:

ALgn> As an exercise, write a loop that traverses the previous list 
ALgn> (['spam!', 1, ['Brie', 'Roquefort', 'Pol le Veq'], [1, 2, 3]]) and 
ALgn> prints the length of each element. What happens if you send an 
ALgn> integer to len? (exercise from 8.3)

ALgn> from the ebook How To Think Like A Computer Scientist: Learning with 
ALgn> Python.

ALgn> I've coded a function to solve this but it doesn't seem to work. IDLE 

ALgn> just hangs when I execute this function.

ALgn> Here's my solution:

ALgn> def exerSize():
ALgn>         exer = ['spam!', 1, ['Brie', 'Roquefort', 'Pol le Veq'], [1, 2, 3]]
ALgn>         i = 0
ALgn>         while i < len(exer):
ALgn>                 len(exer[i])
ALgn>         i = i + 1
                

ALgn> Thanks in advance!
ALgn> -Anwar

BTW: the common idiom in Python for iterating through the list is:

for item in exer:
    # do something

For example, your exercise with note by Michael Janssen (see the
letter for more details) might look:

def printLens(l):
    for item in l:
        try:
            print len(item)
        except TypeError:
            print "No len for", item
            
if __name__ == "__main__":
    printLens(['spam!', 1, ['Brie', 'Roquefort', 'Pol le Veq'], [1, 2, 3]])


-- 
Best regards,
 anton                            mailto:antonmuhin@rambler.ru