Newbie question: Allocation vs references
rzed
jello at comics.com
Thu Jun 2 08:56:41 EDT 2005
Jan Danielsson <jan.danielsson at gmail.com> wrote in
news:429efdbf$1 at griseus.its.uu.se:
> Hello all,
>
> Behold:
>
> ----------
> a = [ 'Foo', 'Bar' ]
> b = [ 'Boo', 'Far' ]
> q = [ a, b ]
>
> print q[0][0]
> print q[1][1]
>
> a[0] = 'Snoo'
> b[1] = 'Gnuu'
>
> print q[0][0]
> print q[1][1]
> ----------
>
> This will output:
> Foo
> Far
> Snoo
> Gnuu
>
> I assume it does so because q stores _references_ to a and b.
> How
> would do I do if I want to copy the list? I.e. I want the output
> from the code above to be:
>
If your original assigment to q were:
q = [ a[:], b[:] ]
... you would have copies of a and b, so that:
>>> a = [ 'Foo', 'Bar' ]
>>> b = [ 'Boo', 'Far' ]
>>> q = [ a[:], b[:] ]
>>> print q[0][0]
Foo
>>> print q[1][1]
Far
>>>
>>> a[0] = 'Snoo'
>>> b[1] = 'Gnuu'
>>>
>>> print q[0][0]
Foo
>>> print q[1][1]
Far
> Foo
> Far
> Foo
> Far
>
> ..even if a[0] = 'Snoo' and b[1] = 'Gnuu' remain where they are.
>
> 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?
That's easier:
>>> a = [ 'Foo', 'Bar' ]
>>> b = [ 'Boo', 'Far' ]
>>> q = [a,b]
>>> a = ['Splee','Hoongk']
>>> b = ['Blik','Poit']
>>> print q[0][0]
Foo
>>> print q[1][1]
Far
You've stuck the 'a' and 'b' labels on new objects this way. The
original objects would vanish except that there is still a reference
to them through the 'q' list.
>
> C equivalent of what I want to do:
> -----------
> a = calloc(n, size);
> prepare(a)
>
> q[0] = a;
>
> a = calloc(n, size); // new list; 'q' is unaffected if I change
> 'a' -----------
--
rzed
More information about the Python-list
mailing list