0

Just learning Python, and, an extremely basic but serious question around mutablility, as I want to understand the core concepts here.

Strings are immuteable, meaning, once a value is assigned it cant be changed. Unlike for example, an integer. This confuses me, because if I run the below code, I can change the value of the string and the integer so ... are they both not muteable?

What is the key concept here I am missing? Is mutability more about the Type? i.e. Type(myString) ..

mystring = "hello"
myint = 1

print(mystring)
print(myint)  

hello
1

 mystring = "nolongerhello"
 myint = 2

print(mystring)
print(myint)

nolongerhello
2

Thanks C

khelwood
  • 55,782
  • 14
  • 81
  • 108
  • 1
    You're not changing the string. You're reassigning the variable. The variable is not the string. – khelwood Jan 28 '21 at 20:29
  • 1
    In Python an int isn't mutable either. when you do `myint = 2` you aren't changing the integer object, you are simply assigning `myint` to refer to a different integer object. Remember immutability is nothing to do with the name and everything to do with the object that the name refers to. – Tony Suffolk 66 Jan 28 '21 at 20:33
  • *“Strings are immuteable, [..u]nlike for example, an integer”* — Integers are just as immutable as strings. – deceze Jan 28 '21 at 20:34
  • Understand what exactly *mutable* means: `a = []; b = a; b.append('foo'); print(a, b)` — Try this kind of thing with strings or integers; it can’t be done. – deceze Jan 28 '21 at 20:37

0 Answers0