Newbie question: Allocation vs references

Jan Danielsson jan.danielsson at gmail.com
Thu Jun 2 08:43:40 EDT 2005


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:

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?

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'
-----------



More information about the Python-list mailing list