0
def func():
    global count
    count += 1


if __name__ == '__main__':
    count = 0
    print(count)
    func()
    print(count)

As defined in the python documentation:

  1. If we have a mutable object (list, dict, set, etc.), we can use some specific operations to mutate it and all the variables that refer to it will see the change.

  2. If we have an immutable object (str, int, tuple, etc.), all the variables that refer to it will always see the same value, but operations that transform that value into a new value always return a new object.

Its clearly mentioned in the 2nd statement that int is immutable, but if you run the python code above with global it seems to be working.

Any explanation that anyone can provide here, or i am missing something here?

Ch3steR
  • 20,090
  • 4
  • 28
  • 58
Mehul
  • 11
  • What part of the official documentation are you referencing? – Iain Shelvington Jan 01 '22 at 05:31
  • 1
    Immutability in Python means you can't modify the contents of the object, not that you can't change what the name pointing to the object is bound to. – Miguel Guthridge Jan 01 '22 at 05:33
  • https://docs.python.org/3/faq/programming.html#how-do-i-write-a-function-with-output-parameters-call-by-reference – Mehul Jan 01 '22 at 05:42
  • @MiguelGuthridge I don't think i am changing the name to point to a different object. – Mehul Jan 01 '22 at 05:50
  • @Mehul your argument is about the statement `count += 1`? You think it is mutating the int object that `count` is pointing to but that statement is actually returning and assigning a new int to `count` – Iain Shelvington Jan 01 '22 at 05:57
  • Use the `id(count)` function to check the ID of the variable before and after - you'll notice it's different. In Python the += operator creates a new copy. – Miguel Guthridge Jan 01 '22 at 06:03
  • @Mehul of course you are changing the object the name refers to, you used: `global count` so now that variable *is the global variable*, not a local variable. And then you *modify* that local variable here: `count += 1`, note, this has **nothing** to do with types and immutability. You could have done `count = 'foobar'` and then outside your function, after you call it, count will be `"foobar"` or `count = [1, 2, 3]` and the same effect will be seen outside the function after it is called – juanpa.arrivillaga Jan 01 '22 at 06:29

0 Answers0