0

I have created function "listappend():"with two arguments.Function can append list value with each function call and return updated value. I am trying to store this updated value into variable which I can but when I call listappend() to update it changes the stored variable value every time when I call a function.

You can see in below given example, list value is [10,20,30] and I have stored with value 40 in varible x. so now x is [10,20,30,40]. I called function with new list value with [50] now it become [10,20,30,40,50]
and the value of x is replaced with new value. Even if you store x into a new variable and call listappend() again with new value then it will replace the value of new variable.

def listappend(a,list=[]): 
   list.append(a)
   return list

listappend(10) # returns [10]
listappend(20) # returns [10, 20]
listappend(30) # returns [10, 20, 30] 
x = listappend(40) 
print(x) # returns [10, 20, 30, 40] 
y = listappend(50) 
print(y) # returns [10, 20, 30, 40, 50]  
print(x) # returns [10, 20, 30, 40, 50, 60]

Moller Rodrigues
  • 780
  • 5
  • 16
Hardik Patel
  • 155
  • 1
  • 9
  • This is because python uses referencing. So x updated everytime listappend is called. And so is y and any other variable related to listappend function. – Onyambu Mar 21 '19 at 23:32
  • It is not recommended to use `list` as a variable name, it hides python's `list` type. – AChampion Mar 21 '19 at 23:33
  • @AChampion Thank you for suggestions. Can you please explain me why it mutate variable's value too, and use of this kind of mutation. – Hardik Patel Mar 22 '19 at 15:45

0 Answers0