0

In detail, my question is this: Given the following code,

x = 10
def func(x):
    x = x+1

def main():
    print(x)
    func(x)
    print(x)

if __name__ == '__main__':
    main()

On running this I get:

10
10

Does this mean that Python does not pass values by reference?

And I did check through the other question of the sort, and most(if not all) included analogies of lists or other such examples. Is it possible to explain this in simple terms, like just a simple integer?

Ps. I am a beginner to coding.

Thanks

Rudra
  • 53
  • 7

1 Answers1

4

If you are coming from a background such as C or C++, which I did, this can be maddening until you figure it out.

Python has names, not variables, and names are bound to objects. Effectively, you can think of all 'variables' or names, as being pointers to python objects.

In python, integers, floats, and strings are immutable. So when you do the following:

x = 10
x = x + 1

You are first binding the name x to the integer 10, then when you evaluate x + 1 you get a new object 11 and then you bind x to that object. Your x inside the function body is local to the function, and when you bind it to 11, the global x remains bound to 10.

If you were to pass a list to the function, and append something to the list, that list would be modified. A list in python is a mutable object. All names bound to the list would refer to the modified list.

As a result, when you pass mutable objects it may seem as if you are passing by reference, and when you pass immutable objects it may seem like you are passing by value.

Eric Appelt
  • 2,843
  • 15
  • 20