Jan Danielsson <[EMAIL PROTECTED]> wrote in
news:[EMAIL PROTECTED]: 

> 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
-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to