Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I copy an immutable object like tuple in Python?

Tags:

python

types

People also ask

Can you copy a tuple in Python?

Copy a tuple. You cannot copy a list with the = sign because lists are mutables. The = sign creates a reference not a copy. Tuples are immutable therefore a = sign does not create a reference but a copy as expected.

Can tuples be copied?

Since tuples are mutable, they cannot be copied. On the other hand, you can copy list items to a new list.

Is tuple immutable object in Python?

Tuples are immutable Besides the different kind of brackets used to delimit them, the main difference between a tuple and a list is that the tuple object is immutable.

How do you duplicate an object in Python?

In Python, we use = operator to create a copy of an object. You may think that this creates a new object; it doesn't. It only creates a new variable that shares the reference of the original object. Let's take an example where we create a list named old_list and pass an object reference to new_list using = operator.


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, [])

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.


try this:

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

And I think adding an empty tuple is much better.