Maintaining a list
Josiah Carlson
jcarlson at nospam.uci.edu
Fri Feb 13 20:14:57 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?
[snip]
> 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.
Work your way through these interactions.
>>> def myrutine(x, mylist=[]):
... mylist.append(x)
... print mylist
...
>>> myrutine(1)
[1]
>>> myrutine(2)
[1, 2]
>>> myrutine(10)
[1, 2, 10]
>>> b = []
>>> myrutine(1, b)
[1]
>>> b
[1]
>>> myrutine(8)
[1, 2, 10, 8]
>>> b
[1]
>>>
One thing you need to remember is that list.append() returns None, not a
new list.
- Josiah
More information about the Python-list
mailing list