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.
Since tuples are mutable, they cannot be copied. On the other hand, you can copy list items to a new list.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With