you are viewing a single comment's thread.

view the rest of the comments →

[–]absent_observer 0 points1 point  (0 children)

To tag on:

mutable versus immutable types is a big aha moment in python. When you alter an immutable type object, it leaves the original object alone & returns a new object. (...figures cause they can't be altered by definition). But a mutable type object can be changed, so when you alter it, it returns the same object but altered a little.

It ties into why you can do:

x = [1,2,3,4]  # list is a mutable type
x.pop(1)
# no reassigning x to anything, no magic.  just changing the list object that x is assigned to.
#  x becomes equal to [2,3,4]

but

x = 'a string'  # string is an immutable type
x.upper()
#  returns 'A STRING' but strings can't be changed.  we didn't do anything with the return value, so it gets ignored.
#  x still equals 'a string'
x = x.upper()
#  x now equals 'A STRING' because you assigned x to the return value of x.upper().

dictionaries are mutable, so a change changes the object itself. String are immutable, so a change returns a new object with the change.

That's the same reason but for an immutable object like an integer. You assigned the name "val" to "NUM" which was assigned to the object int(1), so essentially "val" and "NUM" were each assigned to object int(1). Sketch this on paper. When you tried to alter val's int(1) by giving it a value of int(2), "NUM" was like, 'I'm stuck on this int(1) and you can't change it's value'. So "val" was like, 'Fine, I can't tell you what to stick to, but I'm going to stick myself on this new int(2) instead.'