this is interesting

4 messages
Open this post in threaded view
|

this is interesting

 >> def f(n, history = []):   history.append(n)   return history >>> f(1)[1]>>> f(2)[1, 2]>>> f(3)[1, 2, 3]>>> f(2)[1, 2, 3, 2]>>> f(1) [1, 2, 3, 2, 1]>>> f(1,[])[1]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?- Michel-- =================================="What I cannot create, I do not understand." - Richard Feynman=================================="Computer science is the new mathematics."- Dr. Christos Papadimitriou================================== _______________________________________________ Edu-sig mailing list [hidden email] http://mail.python.org/mailman/listinfo/edu-sig
Open this post in threaded view
|

Re: this is interesting

 -----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----- _______________________________________________ Edu-sig mailing list [hidden email] http://mail.python.org/mailman/listinfo/edu-sig