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

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

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)