0

In the following function:

def f(value,values):
    value = 4
    values[0] = 100
t = 1
v = [1,2,3]
f(t,v)
print(t,v[0])

Output: 1, 100

The value of t has not changed but the value of v[0] has changed. Can anybody please explain what is happening?

juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172

2 Answers2

0

In python, assignment means binding a name to a object. So

t = 1
v = [1,2,3]

means binding t to object integer 1, binding v to object list [1,2,3]. And in function f(value, values), binding new name value to the same integer 1 and binding new name values to same list [1,2,3]. Now we know:

         --------                 -----------
t     -> | obj1 |       v      -> |  obj2   |
value -> |   1  |       values -> | [1,2,3] |
         --------                 -----------

then statements

    value = 4
    values[0] = 100

mean that name value is re-binded to object integer 4 (because integer is immutable type, so the object itself cannot be changed), and the first element of object [1,2,3] is changed to 100 (list is mutable type).

         --------                 -------------
t     -> | obj1 |       v      -> |  obj2     |
         |   1  |       values -> | [100,2,3] |
         --------                 -------------
         --------
value  ->| obj3 |
         |   4  |
         --------

So t and v still bind to original objects, but object list [1,2,3] is changed to [100,2,3] .

ZMJ
  • 337
  • 2
  • 11
0
def f(value,values):
    value = 4
    values[0] = 100
t = 1
v = [1,2,3]
f(t,v)
print(t,v[0])

let start walking through you code, you are defining a function f:

def f(value,values):
    value = 4
    values[0] = 100

this function takes 2 parameter value and values, ok now move to the code after function

t = 1         # here you are declaring a variable name 't' and have value 1 
v = [1,2,3]   # here we have 'v' having value [1,2,3] which is a list
f(t,v)        # here you are calling the function 'f' which is declare above

Ok, now our main work start when you are calling function 'f' f(t,v) with two parameter having value t=1 & v=[1,2,3] when these parameter reaches our function f(value,values) we have value = 1 and values = [1,2,3].

after that, we have value=4 inside our function so as we have value = 1 previously then our code will like :

value=4  #  previously we have value = 1 so now our code update the value to 4, t does not updated here. 

after that we have values[0]=100 so we have values as [1,2,3] this becomes like:

values[0]=100 # => [1,2,3][0] = 100 so the array [1,2,3] have 1 on index 0 it will replace 1 in array and now our array becomes [100,2,3]

when we do print(t,v[0]) we have t=1 and v[0]=100 because we didn't update the value of t inside our function only the value of our array [1,2,3] get update to [100,2,3]

Abhishek-Saini
  • 733
  • 7
  • 11