Using dicts and lists as default arguments of functions
Johan
johan at notused.invalid
Mon Aug 9 11:19:17 EDT 2010
Dear all,
Considering this test program:
def tst(a={}):
print 1, a
a['1'] = 1
print 2, a
del a
def tstb(a=[]):
print 1, a
a.append(1)
print 2, a
del a
tst()
tst()
tstb()
tstb()
With output:
tnjx at tnjx:~/tst> python tt.py
1 {}
2 {'1': 1}
1 {'1': 1}
2 {'1': 1}
1 []
2 [1]
1 [1]
2 [1, 1]
Would there be a way to ensure that the results does not depend on the
previous call of the function. The desired output is:
1 {}
2 {'1': 1}
1 {}
2 {'1': 1}
1 []
2 [1]
1 []
2 [1]
I know that tst({}) and tstb([]) will work, but is there any way to
still use tst(), tstb()?
Thanks in advance,
Best regards,
Johan
More information about the Python-list
mailing list