How to append a modified list into a list?
Steve D'Aprano
steve+python at pearwood.info
Fri Nov 18 22:01:10 EST 2016
On Sat, 19 Nov 2016 12:44 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'.
[...]
> Obviously the most intuitive way doesn't work.
> def apl0(tbl):
> m.append(tbl)
That works perfectly -- it just doesn't do what you want.
It sounds like what you want is to append a COPY of the list rather than the
list itself. I'm not sure why, making copies of things in Python is usually
rare, but perhaps I don't understand what you are doing with this "working
list" and "recording list".
The simplest way to do this is:
m.append(tbl[:]) # use slicing to make a copy
In newer versions of Python, you can do this:
m.append(tbl.copy())
But that won't work in Python 2.7. Or you can do this:
from copy import copy
m.append(copy(tbl))
But the most Pythonic way (the most standard way) is to use a slice to copy
the list: m.append(tbl[:])
> and introducing a local variable will not help either.
> def apl1(tbl):
> w=tbl
> m.append(w)
Of course not. Assignment does not make a copy.
--
Steve
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.
More information about the Python-list
mailing list