0

I am trying to understand a strange thing in Python. I created a dictionary in Python, assigned the dictionary values to a temporary variable, and then cleared all the values in the temporary variable. Strangely, the values in the dictionary also got cleared. What could be the reason behind it ?

For example, in cases where I do not want to affect the main variable, and just do something in the temporary variable, this will never work. Is there a workaround ?

Below is the steps that I tried to execute

dict = {'random' : [1, 2, 3, 4, 5]}
data = dict['random']
data
[1, 2, 3, 4, 5]
data.clear()
dict
{'random': []}
Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
Masoom Kumar
  • 129
  • 1
  • 8
  • 1
    TLDR: There is only *one single* object ``[1, 2, 3, 4, 5]`` created in this code. It is known to Python both as ``dict['random']`` and ``data``. You must explicitly copy it if you want to create a second object with the same value. – MisterMiyagi Sep 09 '21 at 14:22
  • @MisterMiyagi : Thank you for the answer. Now I managed to fix the problem with the suggestions – Masoom Kumar Sep 09 '21 at 14:37

1 Answers1

1

Setting data = dict['random'] just binds "data" to the array inside "dict", it doesn't copy it.

Look at Python Copy which explains it in a bit more depth and how to actually copy rather than bind.

clarj
  • 1,001
  • 4
  • 14