1

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.

8
  • 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. Commented Sep 26, 2019 at 22:59
  • 1
    Take a look at PyTuple_SetItem, but don't tell anyone I told you about it. Commented Sep 26, 2019 at 22:59
  • 1
    Interesting article on tuples being immutable except when they hold a reference to another object such as a list --radar.oreilly.com/2014/10/… Commented Sep 26, 2019 at 23:00
  • 1
    If you're going to even attempt to manipulate the raw computer memory you'll be in for a world of pain Commented Sep 26, 2019 at 23:03
  • 1
    @DarrylG no, they are still immutable. Commented Sep 26, 2019 at 23:35

1 Answer 1

-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])
Sign up to request clarification or add additional context in comments.

3 Comments

Yep. Tuples are only as immutable as the objects inside them.
This is just an obfuscated way of doing t[1].append(1). It's not really in the spirit of the question.
The tuple isn't being mutated here

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.