In python, tuples are considered immutable. However, I want to know if tuples can be modified by editing the computer's memory. In order to edit the computer's memory, I was thinking that I could invert the built in id
function in order to write to that memory location the new tuple. I am curious about this because I want to know out of curiosity if tuples are really as immutable as they were designed to be.
Asked
Active
Viewed 128 times
1

Number File
- 197
- 1
- 6
-
6“if tuples are really as immutable as they were designed to be.” — Yes, they are immutable *as they are designed to be*. Subverting the type system by hacking memory locations doesn’t change that because tuples are *not* designed for that use-case. – Konrad Rudolph Sep 26 '19 at 22:59
-
1Take a look at [`PyTuple_SetItem`](https://docs.python.org/3/c-api/tuple.html#c.PyTuple_SetItem), but don't tell anyone I told you about it. – wim Sep 26 '19 at 22:59
-
1Interesting article on tuples being immutable except when they hold a reference to another object such as a list --http://radar.oreilly.com/2014/10/python-tuples-immutable-but-potentially-changing.html – DarrylG Sep 26 '19 at 23:00
-
1If you're going to even attempt to manipulate the raw computer memory you'll be in for a world of pain – Sayse Sep 26 '19 at 23:03
-
Specifically, [this answer](https://stackoverflow.com/a/38706483/2886575) answers this question in the positive for integers (which are also immutable in python), and could be extended to tuples with a little effort. – Him Sep 26 '19 at 23:15
-
1@DarrylG no, they are still immutable. – juanpa.arrivillaga Sep 26 '19 at 23:35
-
@juanpa.arrivillaga: I can change the content of a list in a tuple (so the entire tuple is not constant). Example. t = (2, [3]); print(hex(id(t))) #0x7fcf9c274690; print(hex(id(t[1]))) # 0x7fcf9c531140; t[1].append(4) print(hex(id(t))) # 0x7fcf9c274690 (same) print(hex(id(t[1]))) # 0x7fcf9c531140 (changed). – DarrylG Sep 27 '19 at 00:11
-
1@DarrylG I understand what you are saying, but yet, *the tuple hasn't changed* – juanpa.arrivillaga Sep 27 '19 at 00:19
1 Answers
-1
This might be interesting example for you
t = (1, [2])
print(t)
try:
t[1] += [1]
except TypeError as error:
print("Error occured", error)
finally:
print(t)
Output:
(1, [2])
Error occured 'tuple' object does not support item assignment
(1, [2, 1])

Nf4r
- 1,390
- 1
- 7
- 9
-
-
2This is just an obfuscated way of doing `t[1].append(1)`. It's not really in the spirit of the question. – wim Sep 26 '19 at 23:01
-