Maintaining a list

Karl Pflästerer sigurd at 12move.de
Sat Feb 14 02:00:57 CET 2004


On 14 Feb 2004, Thomas Philips <- tkpmep at hotmail.com wrote:

> 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)
>     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"]
[...]
> 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.

So if you don't want to use a class and not a global var create a
closure or use the feature that an optional argument gets evaluated an
bound the time the function is defined.

So if you write:

>>> myfunc(1)
[1]
>>> myfunc(2)
[1, 2]
>>> myfunc(3)
[1, 2, 3]

always the list which had been created when the function was defined
gets used.  You see that if you change the definition a bit.

>>> def myfunc (item, lst = []):
...     lst.append(item)
...     print id(lst)
...     return lst
... 
>>> myfunc(1)
10484012
[1]
>>> myfunc(2)
10484012
[1, 2]
>>> ##but
... myfunc(1, [])
10485068
[1]
>>> myfunc(3)
10484012
[1, 2, 3]


That may be what you want.

Another option is a closure.

>>> def make_func ():
...     lst = []
...     def func (item, lst = lst):
...         lst.append(item)
...         return lst
...     return func
... 
>>> myfunc = make_func()
>>> myfunc(1)
[1]
>>> myfunc(2)
[1, 2]
>>> 



   KP

-- 
You know you've been sitting in front of your Lisp machine too long
when you go out to the junk food machine and start wondering how to
make it give you the CADR of Item H so you can get that yummie
chocolate cupcake that's stuck behind the disgusting vanilla one.



More information about the Python-list mailing list