Skip to content
Exercise · Q7

Q.Prove with the help of an example that the variable is rebuilt in case of immutable data types.

Yanam BieapTextbookSubjective· 3mImportance★★★★★est
97% · 29/30 Questions
🔒 Locked · start free trial →

You're viewing a preview — the full solution, concept, methods & PYQ mapping are locked.

Start your 14-day free trial to unlock the full solution →

Compare id() before and after "changing" an int or a string: the identity changes, proving Python built a brand-new object — immutable variables are rebuilt, never edited in place.

The idea. Data types like int, float, str and tuple are immutable — once an object is created, its value can never change. So a statement like x = x + 5 cannot modify the object 10; Python evaluates x + 5, creates a new object 15, and rebinds the name x to it. The tool that proves this is the built-in id() function, which returns a unique identity (roughly, the memory address) of the object a name is currently bound to. If the variable were updated in place, id() would stay the same; if it is rebuilt, id() changes.

Proof by example:

x = 10
print("x =", x, "id =", id(x))
x = x + 5          # x is REBUILT: a brand new int object is created
print("x =", x, "id =", id(x))

s = "Hello"
print("s =", s, "id =", id(s))
s = s + " World"   # strings are immutable too - s is rebuilt
print("s =", s, "id =", id(s))

Sample run (the actual id values will differ on every machine and every run — what matters is that they CHANGE):

x = 10 id = 140722972386376
x = 15 id = 140722972386536
s = Hello id = 2079190860208
s = Hello World id = 2079190873328

What this shows, line by line: …

Unlock everything free for 14 days

  • Full step-by-step solutions
  • Concept-first explanations
  • Methods, shortcuts & mistakes
  • PYQ mapping + timed mock tests

Full access for 14 days. No credit card required.