[Tutor] How to control list input ?

Glen Wheeler gew75 at hotmail.com
Thu Jun 3 17:52:39 EDT 2004

  Hi Michele,

  You can use len(..) to check then length of a list, eg

if len(l) == 10:
    raise "LengthError"

  Easier on the eyes is:

if len(l) != 10:
    raise ...
<rest of code here>

  There is no real need for you to strictly define the structure of your
list.  Just make sure you check the input for any errors.  Always know what
your functions are getting as input arguments.
  In other words, say you were looking for a list of lists, three lists, of
lengths 3, 9 and 27.  Then something like:

# l is the list of lists
if len(l) != 3 and len(l[0]) != 3 and len(l[1]) != 9 and len(l[2]) != 27:
    raise ...
<rest of code>

  Better would be to write some kind of list-structure-checking function.
But let's leave that as an exercise ;).


----- Original Message ----- 
From: "Michele Alzetta" <michele.alzetta at aliceposta.it>
To: "Python Tutor" <tutor at python.org>
Sent: Friday, June 04, 2004 2:39 AM
Subject: [Tutor] How to control list input ?

> For a program I'm fooling about with I created the following class
> (still largely incomplete):
> class Template:
>     def __init__(self,doctdbname):
>         self.doctor = shelve.open(doctdbname, writeback = True)
>     def addDoctor(self, doctname, doctlist):
>         self.doctor[doctname] = doctlist
>     def printDoctor(self, doctname):
>         self.doctor[doctname]
>     def alterDoctor(self, doctname, index1, index2, newvalue):
>         self.doctor[doctname][index1][index2] = newvalue
> For my purposes doctlist can't be just any arbitrary list of lists; it
> will have to be made of a precise number of elements, that musn't be
> hardcoded but definable; how do you suggest I try coding a) a way in
> which to define what the structure of my list ought to be like and b) a
> way of checking the input to make sure it corresponds ?
> -- 
> Michele
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor

More information about the Tutor mailing list