(Jan-15-2024, 01:35 AM)johnywhy Wrote:no, what this does is(Jan-15-2024, 12:34 AM)sgrey Wrote: if you say x = 101 you cannot modify 0
Unclear. x is mutable. I can say
x+=1
x = x + 1
. You are assigning a new value to the variable that overwrites the old one. You cannot change the value that is already assigned to x, you can only assign a new value to it. Think about it this way: x is a variable, you can change x to anything you want. But the contents of what that variable holds are a different story. You can easier see this with strings.
Say you have
s = 'john'
. You want to modify it so that the first letter is capital. If it was mutable, you would be able to say s[0] = 'J'
, and that would work. But you cannot do that because strings are immutable. You can call s[0] and get a 'j' in return, but you cannot assign a new value to it. You have to create a new string "John" and assign it to s. It's the same when you add strings together. If do s += ' Smith'
, you are not going to get ' Smith' to be appended to the old value. What will happen is python will create a new string in a new memory location for you with the contents 'John Smith', and then assign that new value to s while the old value will be garbage collected later on.Here, reading material about immutability https://realpython.com/python-mutable-vs...ble-types/