0
def func(x):
    print "inside function" ,id(x)
    x = 2
x = 50
print "outside function" ,id(x)
print 'Value of x before function call is', x
func(x)
print 'Value of x after function call is', x

output:

outside function 6486996
Value of x before function call is 50
inside function 6486996
Value of x after function call is 50

Assuming that id() gives memory location of object. Even though both are saving at the same location, if x value is changed in func(), it is not effected outside.

user1423015
  • 593
  • 1
  • 4
  • 12

3 Answers3

3

Ah, but the id(x) call in the function references the global x that was passed to the function, but the x = 2 creates a new local x. Try this:

def func(x):
    print "inside function", id(x)
    x = 2
    print "still inside function", id(x)

x = 50
print "outside function" , id(x)
print 'Value of x before function call is', x
func(x)
print 'Value of x after function call is', x

typical output

outside function 168950596
Value of x before function call is 50
inside function 168950596
still inside function 168951172
Value of x after function call is 50
user590028
  • 11,364
  • 3
  • 40
  • 57
PM 2Ring
  • 54,345
  • 6
  • 82
  • 182
0

if u want know more about it, i think u need understand basic python fully.

point about your question:

mutable object as parameter

The function gets a reference to that object and could mutate it, but if you re-bind the reference in the method, outer scope know nothing,after done, the outer reference would still point the original object.

immutable object as parameter

Still can't re-bind the outer reference, and can't even mutate this object.

update for comments: so u pass x(Integer immutable) to function call, you can't mutate this object. and u you re-bind the x refer in the function, outer scope know nothing,after done, the outer reference would still point the original integer 50 object.

ssskip
  • 259
  • 1
  • 6
0

An assignment usually changes the binding between name and object (if you don't do sth like x = x, of course). It doesn't do any alterations on the object (which wouldn't work on ints anyway as they are immutable, but just as a side note)

So in this case your x inside the function points to the 50 object until you change it. Then it points to a different object. The object itself is not affected.

To point out what happens step by step:

  • outside x points to int object with value 50
  • function call: inside x points to same object
  • inside x is changed to point to different object, having value 2
  • return: outside x still points to 50.
glglgl
  • 89,107
  • 13
  • 149
  • 217