Q: List and Dicts as default args
Stefan Migowsky
smigowsky at dspace.de
Mon Apr 3 05:53:11 EDT 2000
Hi,
I was just wondering how to handle lists and dictionaries in
a simple way as default arguments to functions. Since following
strange behaviour occured :
>>> def f(Index,List = [], Dict = {}):
... List.append(1)
... List.append(2)
... print List
... Dict[Index] = Index
... print Dict
>>> f(1)
[1, 2]
{1: 1}
>>> f(2)
[1, 2, 1, 2]
{2: 2, 1: 1}
>>> f(3)
[1, 2, 1, 2, 1, 2]
{3: 3, 2: 2, 1: 1}
This behaviour only occurs with dictionaries and list. All other
types are "well" behaved. I could try the following but that
doesn't look so nice:
def f(Index,List = None, Dict = None):
if not List: List = []
List.append(1)
List.append(2)
print List
if not Dict: Dict = {}
Dict[Index] = Index
print Dict
Thanks for any advice.
Stefan
More information about the Python-list
mailing list