5

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

0

6 Answers 6

9

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

Sign up to request clarification or add additional context in comments.

Comments

8

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]

Comments

4

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.

Comments

1

make a copy of the list when append.

  alist2.append(alist[x][:])

Comments

1

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.

Comments

0

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][:])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.