0
x=({1,2},{2,3},{3,4})  # a tuple of sets
y=list(x)              # list based on x
y[1].remove(2)
print 'x', x, 'id', id(x)    # ({1, 2}, {3}, {3, 4})
print 'y', y, 'id', id(y)    # [{1, 2}, {3}, {3, 4}]
# elements in x and y share a same memory
# id(x[i]) = id(y[i])
for element in x:
    print element, 'id', id(element)
for element in y:
    print element, 'id', id(element)

Hi, I need a better way to create a list (or other iterable types) without linked memories. Please find the above Python codes. I intend to create a new list based on a tuple of sets and try to keep the tuple x unchanged while manipulating the list y. However, the elements (which are sets) share a same memory (indicated by their ids). I have found this when the elements are of types like list, tuple, set. Is there a smart and direct way to avoid this? Thanks in advance!

zhuce
  • 13
  • 1
  • 1
    Yes, using deep copy helps. Changing y=list(x) into y=list(copy.deepcopy(x)) can solve the problem. But, is there a more elegant way to do this? – zhuce Jun 29 '16 at 12:45
  • I'm glad to hear it. I think you can mark your question as a duplicate of the one I provided yourself if you wouldn't mind (_duplicates can be useful signposts_). – miradulo Jun 29 '16 at 12:48
  • @zhuce what do you mean "more elegant way to do this?" The elements of x and y **point to the same objects** so a deep copy is **the only way to do it**. Other then manually creating the deep copy with `y = [set(item) for item in x]` which will only work when every element is a set and not any deeper nested structure. – Tadhg McDonald-Jensen Jun 29 '16 at 13:03

0 Answers0