Maintaining a list

Peter Otten __peter__ at web.de
Fri Feb 13 19:47:03 EST 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?
> 
> I'd like to write something of the form
> def myroutine(x)
>     mylist = mylist.append(x)

append() returns None

>     print mylist
>     .
>     .
>     return
> 
> I'd like to call myroutine over and over again from a main program,
> and want it to display the following behavior
> 
> 1. The first time myroutine is called
> myroutine("Item 1")
> ["Item 1"]
> 
> 2. The second time myroutine is called
> myroutine("Item 2")
> ["Item 1", "Item 2"]
> 
> 3. The third time myroutine is called
> myroutine("Item 3")
> ["Item 1", "Item 2", "Item 3"]
> 
> etc. etc.
> 
> 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.
> 
> Sincerely
> 
> Thomas Philips

You're lucky, what you desired as a feature is a common pitfall: default
parameters are only initialized once:

>>> def myroutine(item, lst=[]):
...     lst.append(item)
...     return lst
...
>>> myroutine("item1")
['item1']
>>> myroutine("item2")
['item1', 'item2']
>>> myroutine("item3")
['item1', 'item2', 'item3']
>>> myroutine("item4")[:] = []
>>> myroutine("item5")
['item5']
>>> myroutine("item6")
['item5', 'item6']

This is just a rare case where you can use a mutable object as a default
argument. When you don't want to provide the possibility to change the list
from outside the function, just return a copy of it:

>>> def myroutine(item, lst=[]):
...     lst.append(item)
...     return lst[:]

Peter



More information about the Python-list mailing list