How to append a modified list into a list?
Ian Kelly
ian.g.kelly at gmail.com
Fri Nov 18 21:35:11 EST 2016
On Nov 18, 2016 6:47 PM, <jfong at ms4.hinet.net> wrote:
I have a working list 'tbl' and recording list 'm'. I want to append 'tbl'
into 'm' each time when the 'tbl' was modified. I will record the change by
append it through the function 'apl'.
For example:
>>>tbl=[0,0]
>>>m=[]
>>>tbl[0]=1
>>>apl(tbl)
>>>m
[[1,0]]
>>>tbl[1]=2
>>>apl(tbl)
>>>m
[[1,0], [1,2]]
How to define this function properly?
Obviously the most intuitive way doesn't work.
def apl0(tbl):
m.append(tbl)
and introducing a local variable will not help either.
def apl1(tbl):
w=tbl
m.append(w)
I figure out a workable way, but looks ugly.
def apl2(tbl):
w=[]
w[:]=tbl
m.append(w)
I know those binding tricks between names and objects. Just wondering if
there is an elegant way of doing this:-)
The important thing is to copy the list, not rebind it.
def apl(tbl):
m.append(tbl[:])
Or:
def apl(tbl):
m.append(list(tbl))
More information about the Python-list
mailing list