Hi there i'm having troubles while copying arrays. I know there is really good posts about this but they dont resolve my problems. First of all Im trying to copy nested arrays so the copy using slice do not work:
new_list = old_list[:]
This does not work when used with nested arrays, and I understand why it doesn't. For my purposes i need to work with nested arrays so i've been using:
new_list = list(old_list)
This does copy correctly nested arrays but has a strange behavior when used inside a method. Here is an example code:
Edited Code:
def copy_and_reset(data):
import copy
events_data=list(data)
reset_to_0(data)
return events_data
def reset_to_0(the_array):
for i, e in enter code hereenumerate(the_array):
if isinstance(e, list):
reset_to_0(e)
else:
the_array[i] = 0
a=[[1,1,1,1,1],[2,2,2,2,2,2],[3,3,3,3,3,3],[4,4,4,4]]
b=copy_and_reset(a)
print a
print b
b=list(a)
a.append([22,22])
print a
print b
And here is the output:
[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0]]
[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0]]
[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0], [22, 22]]
[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0]]
Some idea what happens there? The only way to correctly copy an array inside a method is:
new_list = copy.deepcopy(old_list)