-2

Why does the code below output {'a': [1, 3, 4, 5, 6, 7, 8, 9], 'b': [1, 3, 4, 5, 6, 7, 8, 9]}

adic = {}  
main_array = [1,2,3,4,5,6,7,8,9]  
adic["a"] = main_array  
adic["b"] = main_array  
array = adic["a"]  
array.remove(2)  
print(adic)

I am not even assigning the new array to a key. Why should 2 be automatically removed from all the arrays in the dictionary. Am i missing something vital?

  • What is your expected output? Also see [How to clone or copy a list in Python?](http://stackoverflow.com/q/2612802) – Bhargav Rao May 30 '16 at 16:11
  • 1
    "I am not even assigning the new array to a key": that's the point! There is no new array, there's only one (mutable!) `list` object in your entire code. – user2390182 May 30 '16 at 16:15
  • I didn't expect the arrays in the dictionary to change. I was only expecting it to change once I had reassigned the array to the key – user2273795 May 30 '16 at 16:39

2 Answers2

1

All your references point to the same list, as you can check by adding:

print(id(adic["a"]))
print(id(adic["b"]))
print(id(array))
print(id(main_array))

On my system:

32707888
32707888
32707888
32707888

Assignment does not create a copy.

There are several ways to copy a list if this is what you want, such as

new_list = list(old_list)

discussed here.

Community
  • 1
  • 1
Andy G
  • 19,232
  • 5
  • 47
  • 69
  • I wasn't trying to a copy a list. What i was trying to do was take out an array that was assigned to "a". I would then remove a number from the array and reassign it to "a" again. However, I couldn't understand why it wasn't working and was instead removing the number from all the arrays. – user2273795 May 30 '16 at 16:45
0

The reason why your output is doing that is because of the lines where you set each adic['value'] = main_array each of those statements is pointing to the same memory address of your main_array so when you do array = adic["a"] that's also pointing to the same memory address and when you remove 2 it's removing 2 from main_array. Because you are removing from main_array, everything that pointed to main_array is also affected.

Seekheart
  • 1,135
  • 7
  • 8
  • Thanks this was what I was looking for. Do you have any solutions as to how I can achieve what I am trying to do, which is changing only one array? – user2273795 May 30 '16 at 16:46
  • Currently, you only have a single list (arrays are lists in Python) so any changes you make will affect all references to the same list. If you want one list to be different then you need to copy the original list, for which a link has been provided. – Andy G May 30 '16 at 16:50
  • you can do the following to change only one array. `second_array = copy.deepcopy(main_array)` – Seekheart May 30 '16 at 19:15