views:

129

answers:

6

I have an double array

alist[1][1]=-1
alist2=[]
for x in xrange(10):
    alist2.append(alist[x])
alist2[1][1]=15

print alist[1][1]

and I get 15. Clearly I'm passing a pointer rather than an actual variable... Is there an easy way to make a seperate double array (no shared pointers) without having to do a double for loop?

Thanks, Dan

A: 

Usually you can do something like:

new_list = old_list[:]

So you could perhaps throw that in your singular for loop?

for x in range(10):
    alist2.append(alist[x][:])
seanmonstar
+1  A: 

make a copy of the list when append.

  alist2.append(alist[x][:])
Dyno Fu
+3  A: 

A list of lists is not usually a great solution for making a 2d array. You probably want to use numpy, which provides a very useful, efficient n-dimensional array type. numpy arrays can be copied.

Other solutions that are usually better than a plain list of lists include a dict with tuples as keys (d[1, 1] would be the 1, 1 component) or defining your own 2d array class. Of course, dicts can be copied and you could abstract copying away for your class.

To copy a list of lists, you can use copy.deepcopy, which will go one level deep when copying.

Mike Graham
+2  A: 

You can use somelist[:], that is a slice like somelist[1:2] from beginning to end, to create a (shallow) copy of a list. Applying this to your for-loop gives:

alist2 = []
for x in xrange(10):
   alist2.append(alist[x][:])

This can also be written as a list comprehension:

alist2 = [item[:] for item in alist]
sth
+4  A: 

I think copy.deepcopy() is for just this case.

msw
Beat me to it by 6 seconds!
Evgeny
blame it on satellite network latency ;)
msw
+1  A: 

If you're already looping over the list anyway then just copying the inner lists as you go is easiest, as per seanmonstar's answer.

If you just want to do a deep copy of the list you could call copy.deepcopy() on it.

Evgeny