[Tutor] confusion with dictionaries
Thomi Richards
thomi at imail.net.nz
Thu Dec 18 20:08:24 EST 2003
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1
Hi guys,
I was playing around with dictionaries, and came across something which I
found rather... unexpected. here's a demonstration:
>>> def foo(l = {}):
... l[random.choice(string.lowercase)] = random.random()
... return l
...
>>> foo()
{'m': 0.33204172040918167}
>>> foo()
{'m': 0.33204172040918167, 'l': 0.49843519723518959}
>>> foo()
{'u': 0.92434722065201858, 'm': 0.33204172040918167, 'l': 0.49843519723518959}
>>> foo()
{'u': 0.92434722065201858, 'm': 0.33204172040918167, 'l': 0.43003419699678858}
>>> foo()
{'u': 0.92434722065201858, 'z': 0.48421207726860993, 'm': 0.33204172040918167,
'l': 0.43003419699678858}
I thought that if the dictionary 'l' was not stored in a variable outside the
function it would be erased whenever the function foo() was terminated.
This is very wierd... can anyone explain this? Furthermore, how can I ensure
that a dictionary is clean when passing it as an optional argument to a
function like this?
Thanks,
- --
Thomi Richards,
http://once.sourceforge.net/
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.3 (GNU/Linux)
iD8DBQE/4k+L2tSuYV7JfuERAmQpAJ4nSzARBW1IyVHQhU8/g132IKbLMgCgjNiZ
0c9MFtRUjplHvFl+dtkg70o=
=S556
-----END PGP SIGNATURE-----
More information about the Tutor
mailing list