[prev in list] [next in list] [prev in thread] [next in thread]
List: python-list
Subject: Re: Newbie question: Allocation vs references
From: Stian =?iso-8859-1?Q?S=F8iland?= <stian () soiland ! no>
Date: 2005-06-02 13:02:13
Message-ID: 20050602130213.GE11767 () itea ! ntnu ! no
[Download RAW message or body]
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
--
http://mail.python.org/mailman/listinfo/python-list
[prev in list] [next in list] [prev in thread] [next in thread]
Configure |
About |
News |
Add a list |
Sponsored by KoreLogic