Velocity Reviews

Velocity Reviews (http://www.velocityreviews.com/forums/index.php)
-   Python (http://www.velocityreviews.com/forums/f43-python.html)
-   -   Re: scope, function, mutable (http://www.velocityreviews.com/forums/t955105-re-scope-function-mutable.html)

Thomas Bach 12-04-2012 11:40 AM

Re: scope, function, mutable
 
Hi,

On Tue, Dec 04, 2012 at 02:55:44PM +0400, gusarer@gmail.com wrote:
> What is the appropriate definition for the following behavior in Python 2.7
> (see code below).


It has something to do with mutability of lists and that Python passes
around references and not the actual objects.

>
> def f1(x):
> x = [44] + x[1:]
> x[1] = 99
>
> def f2(x):
> x[1] = 99
> x = [44] + x[1:]
> x[3] = 99
>
> t = [1,2,3,4,5,6,7]
> f1(t)
> print t # [1, 2, 3, 4, 5, 6, 7]
> t = [1,2,3,4,5,6,7]
> f2(t)
> print t # [1, 99, 3, 4, 5, 6, 7]


Put that code in e.g. file.py and run

python -m pdb file.py

this will drop you off in the debugger. Step through your code line by
line (using ‘s’) and see how the function calls affect your list
(e.g. via ‘print x’/‘print t’). If this confuses you further… Well,
tell me that my autodidact methodology did not work out at all and ask
again. ;)

Regards,
Thomas.


All times are GMT. The time now is 08:45 PM.

Powered by vBulletin®. Copyright ©2000 - 2014, vBulletin Solutions, Inc.
SEO by vBSEO ©2010, Crawlability, Inc.