title: Efficiently merge two objects in python
body: <p>I have a two objects that I want to merge in such a way that all references to the two merged objects now point to the one merged object.</p>
  
  <pre><code>#What I want
  listOfObjects=[obj1, obj1, obj2, obj2, obj3]
  mergeObjects(obj1, obj2)
  #now
  listofObjects==[merged, merged, merged, merged, obj3]
  </code></pre>
  
  <p>One way to accomplish it is this:</p>
  
  <pre><code>def mergeObjects(obj1, obj2):
      obj1.property1+=obj2.property1
      obj1.property2+=obj2.property2
      obj2=obj1
  </code></pre>
  
  <p>However, this has the downside that rather than having one merged object, I have a merged object and an identical copy of it. My program will merge dozens of objects with each other, so this will consume far too much memory.</p>
  
  <p>Another way is:</p>
  
  <pre><code>listOfObjects=[obj1, obj1, obj2, obj2, obj3]
  mergeObjects(obj1, obj2)
  for i in range(len(listOfObjects)):
      if (listOfObjects[i]==obj2):
          listOfObjects[i]==obj1
  #now
  listofObjects==[merged, merged, merged, merged, obj3]
  #and obj2 is now free to be garbage collected
  </code></pre>
  
  <p>However, there are multiple references to these objects and iterating over every one of them each time I merge an object is also not optimal.</p>
  
  <p>One thing I thought of is if I could use pointers. I could instead store a list of pointers to objects and then write:</p>
  
  <pre><code>def mergeObjects(obj1_pointer, obj2_pointer):
      obj1=&amp;obj1_pointer
      obj2=&amp;obj2_pointer
      obj1.property1+=obj2.property1
      obj1.property2+=obj2.property2
      obj2_pointer=obj1_pointer
      #let's say the pointers are themselves objects so now we have:
  
      listOfPointers==[obj1_pointer, obj1_pointer, obj1_pointer, obj1_pointer, obj3_pointer]
      #obj1_pointer is now pointing to the merged object
      #obj2 now has no references so is free to be deleted
  </code></pre>
  
  <p>Where I'm using &amp; as the dereference operator.</p>
  
  <p>So would writing my own pseudopointer object with a dereference method that returned an object be an efficient solution?</p>
  
  <p>If not is there a cleaner way to do this (change object 1 to merged object, then have all references to object 2 instead be a reference to object 1)?</p>