-1
def check(val, list=[]):
    list.append(val) 
    return list

list1=check("a")
list2=check("b",[])
list3=check("c")

If I run list1 and check the output it shows ["a"]

But, If I run list1, list2 and list3 in one cell and check for list1 it shows ['a','c'], can someone please explain why is it so?

BeRT2me
  • 12,699
  • 2
  • 13
  • 31
Anonamous
  • 253
  • 2
  • 3
  • 14
  • It can save its own list you can provide it here `list2=check("b",[])` – Mehmaam Nov 01 '22 at 05:58
  • Please avoid using `list` as a variable/argument name. It is a builtin function. But your actual problem is using [] as a default assignment. That reference is created at function definition and sticks with subsequent calls. The proper technique is to use None for the default and at the start of the function check for None, and assign it [] (a new list). – RufusVS Nov 01 '22 at 06:02
  • Does this answer your question? [How can I avoid issues caused by Python's early-bound default parameters (e.g. mutable default arguments "remembering" old data)?](https://stackoverflow.com/questions/366422/how-can-i-avoid-issues-caused-by-pythons-early-bound-default-parameters-e-g-m) – Jorge Luis Apr 19 '23 at 11:13

2 Answers2

2

This is the right way to do this:

def check(val, values=None):
    if values is None:
        values = []
    values.append(val)
    return values


list1 = check("a")
list2 = check("b", [])
list3 = check("c")

Default argument values should not be mutable. You can find a good explanation here, And list is a poor name for a variable, because list is a built-in type, as are str, set, dict.

ChamRun
  • 104
  • 6
-2

It seems that list1 and list3 share same object.

You can try this:

def check(val, list=[]):
    list.append(val)
    print(hex(id(list)))
    return list

list1=check("a")
list2=check("b")
list3=check("c")

print(list1)
print(list2)
print(list3)
Alex Liao
  • 25
  • 3