0

I have a slight confusion (still beginning with Python) about the ownership of an object. I have the following code:

dict = {}
list = []

for i in [1,2,3]:
    obj = {}
    obj[str(i)] = i
    list.append(obj)
    dict[str(i)] = obj

print dict
print list

for t in list:
    t["s"] = 42

print dict
print list

which prints

{'1': {'1': 1}, '3': {'3': 3}, '2': {'2': 2}}
[{'1': 1}, {'2': 2}, {'3': 3}]
{'1': {'1': 1, 's': 42}, '3': {'3': 3, 's': 42}, '2': {'s': 42, '2': 2}}
[{'1': 1, 's': 42}, {'s': 42, '2': 2}, {'3': 3, 's': 42}]

so I have "deducted" that python stores "references" to an object instead of a copy to an object when an object is stored in two separate containers.

Is this the default way python handles objects? And in which circumstances can I encounter a situation when python will store a copy of an object in a container?

Ferenc Deak
  • 34,348
  • 17
  • 99
  • 167
  • There is no such thing as 'ownership', names are just *references* to objects. You can create multiple references to any one object. To create copies, do so explicitly. – Martijn Pieters Sep 24 '14 at 09:30
  • And to create a shallow copy of a dictionary: [How to copy a dictionary and only edit the copy](http://stackoverflow.com/q/2465921) – Martijn Pieters Sep 24 '14 at 09:32
  • @MartijnPieters Ok, thanks a lot for pointing to the correct answers! – Ferenc Deak Sep 24 '14 at 09:33

0 Answers0