How Can I Copy An Immutable Object Like Tuple In Python?
copy.copy() and copy.deepcopy() just copy the reference for an immutable object like a tuple. How can I create a duplicate copy of the first immutable object at a different memory
Solution 1:
You're looking for deepcopy
.
from copyimport deepcopy
tup = (1, 2, 3, 4, 5)
put = deepcopy(tup)
Admittedly, the ID of these two tuples will point to the same address. Because a tuple is immutable, there's really no rationale to create another copy of it that's the exact same. However, note that tuples can contain mutable elements to them, and deepcopy/id behaves as you anticipate it would:
from copyimport deepcopy
tup = (1, 2, [])
put = deepcopy(tup)
tup[2].append('hello')
print tup # (1, 2, ['hello'])
print put # (1, 2, [])
Solution 2:
Add the empty tuple to it:
>>>a = (1, 2, 3)>>>a is a+tuple()
False
Concatenating tuples always returns a new distinct tuple, even when the result turns out to be equal.
Solution 3:
try this:
tup = (1,2,3)
nt = tuple(list(tup))
And I think adding an empty tuple is much better.
Post a Comment for "How Can I Copy An Immutable Object Like Tuple In Python?"