0

I've been playing with python arrays for a while, But recently I faced with a weird problem. Here's my code:

import numpy as np

myarr = [
    ["s"],
    ["s"],
    ["w"],
    ["p"],
    ["m"],
    ["g"],
    ["c"]
]

newarr = list(myarr)
print(id(myarr))
print(id(newarr))

print(myarr, "myarr")
print(newarr, "newarr")
print("##### starting manipulation #########")

for i in newarr:
    i[0] = "a"

print(myarr, "myarr")
print(newarr, "newarr")

My problem is even when I copy the "myarr" array into a new array called "newarr", when I make some changes in the "myarr", or the "newarr", both of them act like referenced arrays (referencing to the same memory address), even though they have different memory id.

I tried it with slicing, or even arr.copy() method, but they both didn't work.

I only can fix it when I use numpy array.

newarr = np.array(myarr)

Where is my problem?

Thank you in advance:)

hpaulj
  • 221,503
  • 14
  • 230
  • 353
Parsa
  • 103
  • 1
  • 7
  • 3
    Possible duplicate of [How to clone or copy a list?](https://stackoverflow.com/questions/2612802/how-to-clone-or-copy-a-list) – Carcigenicate Mar 21 '19 at 17:21
  • 1
    You're making a shallow copy, not a deep copy. The inner lists aren't copied, only the outer one is. Check the id's of the inner lists. – Carcigenicate Mar 21 '19 at 17:22
  • 1
    If you know your data has only 2 levels, you can get a deep copy very simply. For example: `newarr = [list(xs) for xs in myarr]`. – FMc Mar 21 '19 at 17:24
  • Why the `numpy` import and tag? You only show lists. – hpaulj Mar 21 '19 at 18:12

1 Answers1

1

You need to use deepcopy

from copy import deepcopy

myarr = [
    ["s"],
    ["s"],
    ["w"],
    ["p"],
    ["m"],
    ["g"],
    ["c"]
]

newarr = deepcopy(myarr)

print(myarr, "myarr")
print(newarr, "newarr")
print("##### starting manipulation #########")

for i in newarr:
    i[0] = "a"

print(myarr, "myarr")
print(newarr, "newarr")

Output :

([['s'], ['s'], ['w'], ['p'], ['m'], ['g'], ['c']], 'myarr')
([['s'], ['s'], ['w'], ['p'], ['m'], ['g'], ['c']], 'newarr')
##### starting manipulation #########
([['s'], ['s'], ['w'], ['p'], ['m'], ['g'], ['c']], 'myarr')
([['a'], ['a'], ['a'], ['a'], ['a'], ['a'], ['a']], 'newarr')