Maintaining a list

Steve dippyd at
Wed Feb 18 08:19:18 CET 2004

Thomas Philips wrote:

> I'm teaching myself programming using Python and want to build a list
> inside a function (rather like using a static variable in a Fortran
> subroutime - the list must not disappear as soon as the subroutine is
> exited). What's the simplest way to do this?
> The list must be initialized to an empty list before the first call,
> and must be preserved between calls. I have not got to object oriented
> programming as yet, so please keep the solution simple.

How about using a global variable? Define a variable in 
your main program:

mylist = []

def myroutine(x)
     global mylist
     print mylist
     return None

Then call it like this:

 >>> myroutine(1)
 >>> myroutine(2)
[1, 2]

and so forth.

There are disadvantages to using global variables, but 
if you are looking for simplicity this is pretty simple.

Steven D'Aprano

More information about the Python-list mailing list