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

3
  • 2
    I think print "a", a should be print "a", self.a, right? Commented Jan 30, 2016 at 20:39
  • Thanks , you are right Commented Jan 30, 2016 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. Commented Jan 30, 2016 at 20:42

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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".

4 Comments

This is incorrect. In python everything is passed by assignment. Here's an explanation: stackoverflow.com/a/986145/1977847
What is difference between passed by assignment and passed by reference or passed by value ? I am little bit confused about this
reading this article should explain the difference: robertheaton.com/2014/02/09/…
Thanks you for guidance

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.