0

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)
jpaugh
  • 6,634
  • 4
  • 38
  • 90
Hristo Ivanov
  • 679
  • 8
  • 25
  • You didn't use your `copy` function in listing. Is it just a typo or actual code? – J0HN Jul 16 '14 at 10:39
  • 2
    That's what deepcopy is for, exactly. As you can imagine, nested lists (why arrays?) are objects with linking to lower level lists objects. So, when you are copying top object it this case, you are copying heirarchy and links to inner objects, which are not duplicating. – soupault Jul 16 '14 at 10:41
  • possible duplicate of [Deep copy a list in Python](http://stackoverflow.com/questions/17873384/deep-copy-a-list-in-python) – Kobi K Jul 16 '14 at 11:00
  • How did the copy using slice not work? It worked for me. – RageCage Jul 16 '14 at 13:52
  • The reason both a and b got reset to 0 is because in copy_and_reset() you set event_data equal to data. Unlike other languages, this doesn't set this new variable equal to the value of the old one. It effectively renames it. This means when you alter b, a will be altered as well because you set b=a. This gave me so much trouble when I was first learning the language. – RageCage Jul 16 '14 at 14:00

1 Answers1

1

When you are copying the list you are just creating a reference to the lists contained in A. Here is a visualaztion of whats happening:

What it looks like

If you want to step though and view whats happening you should check out PythonTutor

Noelkd
  • 7,686
  • 2
  • 29
  • 43