Re:Python Lists vs. Tuples
by shoyer on Friday August 19, 2016 @10:15PM
(#12324772)
You can't replace a value in a tuple, but you can modify it, e.g.,
[ Parent
| on HN ]
...Or can you?
import ctypes
def tuple_setitem(t, index, item):
obj = ctypes.py_object(t)
item = ctypes.py_object(item)
ref_count = ctypes.c_long.from_address(id(t))
original_count = ref_count.value
if original_count != 1:
ref_count.value = 1
ctypes.pythonapi.Py_IncRef(item)
ctypes.pythonapi.PyTuple_SetItem(obj, ctypes.c_ssize_t(index), item)
ref_count.value = original_count
>>> x = (1, 2, 3,)
>>> tuple_setitem(x, 1, "foo")
>>> x
(1, "foo", 3)
Disclaimer: for entertainment purposes only, do not try this at home!
Re:Python Lists vs. Tuples
by nemothekid on Friday August 19, 2016 @10:39PM
(#12324878)
You haven't changed anything about the tuple. The holds a reference to a list and will always hold a reference to that list.
What you did was modify the underlying list, the tuple itself is immutable.
> You can't replace a value in a tuple, but you can modify it
If it has mutable items in it, yes. But in that case, the tuple can't be used as a dictionary key; Python checks, not just that the tuple itself is immutable, but that every object in it is immutable.