[Edu-sig] this is interesting

Corey Richardson kb1pkl at aim.com
Wed Jun 8 06:58:35 CEST 2011


-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

On 06/08/2011 12:51 AM, michel paul wrote:
>>> def f(n, history = []):
>   history.append(n)
>   return history
>   [...]
> A student wrote me wondering why his function wouldn't 'clear' after being
> called.  He meant to create an empty list and ended up with something like
> this.
> 
> What's a good way to explain what's going on?
> 

It's a very, *very* common newbie mistake. When the function object is
created, the "history=[]" is evaluated and it refers to the same object
during each run of the function. The proper idiom is:

def f(n, history=None):
    if history is None:
        history = []
    # Do stuff

I probably explained that poorly but it's essentially what's going on.
- -- 
Corey Richardson
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v2.0.17 (GNU/Linux)

iQEcBAEBAgAGBQJN7wF7AAoJEAFAbo/KNFvpm+cH/jd/7t3/ShChjwskEL/93pz0
qzIEm+ZhJX2+Y/4IQGznuxn7SFnhx9NpjG77zUCVGO0uscfks6b1MpcU+7LBuDcO
N2qaTbQsJf5oy83Y9CCjJr6KUcqZVcr0/2cA7dmFkAnAmizB5/q+N1KVI/KcCDcj
rdy9P/l4tVG/HmJjPgoNGQAcfZALL/5DmkHzf5evgy6aCttdDX3G6tjRneU4Vn9c
f7OE8A7t1/uyHLh6tV0S1F2skuJIig4BVXsvCuOCCXw/dPpqnwoTPrhbdOA085tJ
Payd/CrM2gZPRSnnOybVJSZGFR2rv9w+91iAsBGIYYCT3BEHMDvImFiNfLOZFus=
=dk4m
-----END PGP SIGNATURE-----


More information about the Edu-sig mailing list