1

I have wrote following code in python

class check(object):
    def __init__(self):
        self.a = [1,2,3,4]
        self.b = 5
        appending(self.a, self.b)
        print "a", self.a
        print "b", self.b

def appending(a,b):
    a.append(5)
    b +=1

If now I run check() function, I got output as following:

a [1,2,3,4,5] [1,2,3,4,5]

b 5 5

So, I have following question

  • Why it is that list(a) is got updated but not int(b)?

  • It is related that I am modifying a but i am creating new object when I add 1 in b, in short, it is difference due to immutable or mutable data types.

  • I have define self.a and self.b in object, i have define a,b in function, then why I can write print a and print b in object, get same output as self.a and self.b

Brendan Abel
  • 35,343
  • 14
  • 88
  • 118
Kush Patel
  • 3,685
  • 5
  • 42
  • 65
  • 2
    I think `print "a", a` should be `print "a", self.a`, right? – Håken Lid Jan 30 '16 at 20:39
  • Thanks , you are right – Kush Patel Jan 30 '16 at 20:41
  • And the simple answer to your question is "yes". It's because the integer is immutable. `self.b` still points to the integer `5`. When you do `b += 1` you create a new integer and assign it to the identifier `b`, but only inside the scope of the function `appending`. – Håken Lid Jan 30 '16 at 20:42

2 Answers2

4

self.b is a name for an integer 5. The integer is an immutable object.

When you appear to mutate b you actually create a new object 6 and assign b as a name for it. This in no way affects the object 5 which self.b is a name for.

Peter Wood
  • 23,859
  • 5
  • 60
  • 99
2

Since a is a list, it's passed by reference to the method and any changed done to it within the method, will be done directly to the a.

Variable b is an integer, therefore it's passed by value and a copy of the variable is created to be used within the method. Any change will be visible only within the body of the method, but not to the "outside world".

Marko Jevtić
  • 29
  • 1
  • 4