This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

classification
Title: python user define function is replacing variable value
Type: enhancement Stage: resolved
Components: macOS Versions: Python 3.7
process
Status: closed Resolution: not a bug
Dependencies: Superseder:
Assigned To: Nosy List: HardikPatel, ned.deily, ronaldoussoren, xtreak
Priority: normal Keywords:

Created on 2019-03-21 22:59 by HardikPatel, last changed 2022-04-11 14:59 by admin. This issue is now closed.

Files
File name Uploaded Description Edit
logical Er HardikPatel, 2019-03-21 22:59
Messages (2)
msg338568 - (view) Author: Hardik (HardikPatel) Date: 2019-03-21 22:59
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) 
[10]
>>> listappend(20) 
[10, 20]
>>> listappend(30) 
[10, 20, 30]
>>> x = listappend(40) 
>>> print(x)
[10, 20, 30, 40]
>>> y = listappend(50) 
>>> print(y)
[10, 20, 30, 40, 50]
>>> z = listappend(60) 
>>> print(z)
[10, 20, 30, 40, 50, 60]
>>> print(x)                  
[10, 20, 30, 40, 50, 60]
>>> print(y)              
[10, 20, 30, 40, 50, 60]
>>> print(z)
[10, 20, 30, 40, 50, 60]
>>>
msg338570 - (view) Author: Karthikeyan Singaravelan (xtreak) * (Python committer) Date: 2019-03-21 23:12
This is expected behavior. Please read : https://docs.python.org/3/faq/programming.html#why-are-default-values-shared-between-objects . Default values are defined when function is created and not for every function call and you are having a reference to the returned list that is mutated. Also please use a better name for default since list is a built-in datatype and can cause confusion.
History
Date User Action Args
2022-04-11 14:59:12adminsetgithub: 80574
2019-03-21 23:28:37zach.waresetstatus: open -> closed
resolution: not a bug
stage: resolved
2019-03-21 23:12:25xtreaksetnosy: + xtreak
messages: + msg338570
2019-03-21 22:59:11HardikPatelcreate