How can I copy an immutable object like tuple in P

2020-05-25 03:41发布

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 location?

标签: python types
3条回答
狗以群分
2楼-- · 2020-05-25 04:21

try this:

tup = (1,2,3)
nt = tuple(list(tup))

And I think adding an empty tuple is much better.

查看更多
Anthone
3楼-- · 2020-05-25 04:28

You're looking for deepcopy.

from copy import 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 copy import deepcopy
tup = (1, 2, [])
put = deepcopy(tup)
tup[2].append('hello')
print tup # (1, 2, ['hello'])
print put # (1, 2, [])
查看更多
一夜七次
4楼-- · 2020-05-25 04:46

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.

查看更多
登录 后发表回答