473,322 Members | 1,734 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,322 software developers and data experts.

Maintaining a list

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)
print mylist
Jul 18 '05 #1
7 1394
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
Jul 18 '05 #2
On 14 Feb 2004, Thomas Philips <- tk****@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.
Jul 18 '05 #3
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
Jul 18 '05 #4
On 14 Feb 2004, Karl Pflästerer <- si****@12move.de wrote:
So if you write:


Here something got lost during c&p
def myfunc (item, lst = []): .... lst.append(item)
.... return lst
....
myfunc(1) [1] myfunc(2) [1, 2] myfunc(3)

[1, 2, 3]


KP

--
He took his vorpal sword in hand:
Long time the manxome foe he sought--
So rested he by the Tumtum tree,
And stood awhile in thought. "Lewis Carroll" "Jabberwocky"
Jul 18 '05 #5
In article <b4**************************@posting.google.com >,
Thomas Philips <tk****@hotmail.com> wrote:

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.


Unfortunately, while the other solutions given fit your technical
requirements, they're also what I (and probably others) would consider
unnatural for Python programs. That's partly because abuse of default
parameters and closures are actually two of the more difficult concepts
for people to learn correctly, IME. Here's a "less-simple" solution that
does what you want in a Pythonic fashion, though it still uses a trick:
class CallableList: .... def __init__(self):
.... self.data = []
.... def __call__(self, x):
.... self.data.append(x)
.... return self.data
.... myroutine = CallableList()
myroutine('1') ['1'] myroutine('spam') ['1', 'spam'] myroutine.data

['1', 'spam']
--
Aahz (aa**@pythoncraft.com) <*> http://www.pythoncraft.com/

"Argue for your limitations, and sure enough they're yours." --Richard Bach
Jul 18 '05 #6
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.


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

mylist = []

def myroutine(x)
global mylist
mylist.append(x)
print mylist
return None

Then call it like this:
myroutine(1) [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

Jul 18 '05 #7
Steve wrote:
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?

...
mylist = []

def myroutine(x)
global mylist
mylist.append(x)
print mylist
return None


For the shortest (not simplest conceptually, but good to learn why it
works) solution, I'd propose:

mylist = []
myroutine = mylist.append
--
-Scott David Daniels
Sc***********@Acm.Org
Jul 18 '05 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
by: John Topley | last post by:
Hi, I'm trying to create a pure CSS layout using DIVs. I have three DIVs (in one column) down the left hand side of my page, with a ten pixel vertical gap between each of them (the content is on...
2
by: Chris | last post by:
Hi, I am building a single webform/webpage asp.net application using VB.NET. I have created lots of classes for this web application. On page load I use a facade controller pattern class to...
27
by: Raymond | last post by:
They say it's easier, but has anyone tried maintaining an ASP.NET site without the source code of the dlls? This was not a problem with classic ASP, all the code was almost always just in text...
10
by: Phuff | last post by:
Thanks in advance! I'm trying to maintain a dl list's selected index on postback. What I'm doing is when a person selects an item from the drop down list I select a date in a calendar control and...
3
by: Mahathi | last post by:
Hi I have a small problem in maintaining the state of a check box. Please do me a favour by telling me the procedure how to do that. My requirement is that "I have to map some roles with...
6
by: itgaurav198 | last post by:
Hi, i have one jsp in which i select a value from drop down and on change of this a servlet is called that accesses some values and return to the same jsp where these values get populated in...
0
by: rcon | last post by:
I'm creating a user control to prompt for crystal reports parameters. The individual controls work fine, and the over all control works fine too. However, I'm not really that experienced in the...
2
by: =?Utf-8?B?RGVyZWs=?= | last post by:
Does anyone know if there is an idiots guide to maintaining Active Directory using VB.NET. I have found bits and pieces about ldap_add, ldap_modify etc on the web but I could do with more hand...
3
by: eschneider | last post by:
Just some common issues with WS: Using custom objects: When objects change, seems you are always fixing some issue. Update references, which sometimes does not work. Deployment: Weird errors...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.