0

With this i am getting desired output that is "we pass mutable objects like list or dictionary and try to update them, their original value will be updated at the same memory address"

def update(arg):
    print('inside the funtion,before update',arg)
    print('Memory address of list inside function, before update',id(arg))
    arg[1]=-3
    print('inside function, after update',arg)
    print('Memory address of list inside function, after update',id(arg))
entry=[1,2,3]
print('item in list',entry)
print('memery location of item',id(entry))
update(entry)
print('items in updated list',entry)
print('memory location of of updated lsit',id(entry))

----------------output------------------- item in list [1, 2, 3] memery location of item 1464404562312 inside the funtion,before update [1, 2, 3] Memory address of list inside function, before update 1464404562312 inside function, after update [1, -3, 3] Memory address of list inside function, after update 1464404562312 items in updated list [1, -3, 3] memory location of of updated lsit 1464404562312

---------------undesired output-----------------

def update(arg):
    print('inside the funtion,before update',arg)
    print('Memory address of list inside function, before update',id(arg))
    arg=[i * 5 for i in arg]
    print('inside function, after update',arg)
    print('Memory address of list inside function, after update',id(arg))
entry=[1,2,3]
print('item in list',entry)
print('memery location of item',id(entry))
update(entry)
print('items in updated list',entry)
print('memory location of of updated lsit',id(entry))

----------output---------- item in list [1, 2, 3] memery location of item 2566433750984 inside the funtion,before update [1, 2, 3] Memory address of list inside function, before update 2566433750984 inside function, after update [5, 10, 15] Memory address of list inside function, after update 2566433750856 items in updated list [1, 2, 3] memory location of of updated lsit 2566433750984


the items in the list didnt get updated and even the memory location remained same as original.

Can anyone please explain me the cause of this change in behaviour due to change in just the arg part ?

1 Answers1

0

arg is a local name referencing the same data that your to the passed in reference references. By assigning arg = [i * 5 for i in arg] you assign a new list to that local name - the outher ref still points to it's data.

Try:

arg[:]=[i * 5 for i in arg]

which will overwrite the old data of the reference with the new data by slice-assignment.

def update(arg):
    return [i * 5 for i in arg]

entry = [1,2,3]
entry = update(entry)

to make it easier to understand.

See How does assignment work with list slices? and https://docs.python.org/3/reference/simple_stmts.html#assignment-statements

Your first code works, because you are modifying the referenced data itself.

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69