Newbie question: Allocation vs references
Stian Søiland
stian at soiland.no
Thu Jun 2 09:02:13 EDT 2005
On 2005-06-02 14:43:40, Jan Danielsson wrote:
> a = [ 'Foo', 'Bar' ]
> b = [ 'Boo', 'Far' ]
> q = [ a, b ]
> Or, better yet, how do I store a and b in q, and then tell Python
> that I want a and b to point to new lists, without touching the contents
> in q?
There are several ways to create a copy of a list:
a1 = a[:] # new copy, sliced from 0 to end
a2 = list(a) # create a new list object out of any sequence
import copy
a3 = copy.copy(a) # use the copy module
So you could do for example:
q1 = [ list(a), list(b) ]
q2 = [ a[:], b[:] ]
q3 = [ list(x) for x in (a,b)]
Note that the copy module also has a function deepcopy that will make
copies at all levels. So if you had:
q = [a,b]
q1 = copy.deepcopy(q2)
every list in q1, even the inner "a" and "b" will be new copies. Note
that non-mutables such as "Foo" and "Bar" are NOT copied, but as they
cannot be changed, that doesn't matter.
--
Stian Søiland Work toward win-win situation. Win-lose
Trondheim, Norway is where you win and the other lose.
http://soiland.no/ Lose-lose and lose-win are left as an
exercise to the reader. [Limoncelli/Hogan]
Og dette er en ekstra linje
More information about the Python-list
mailing list