scope, function, mutable

Thomas Bach thbach at students.uni-mainz.de
Tue Dec 4 12:40:32 CET 2012


Hi,

On Tue, Dec 04, 2012 at 02:55:44PM +0400, gusarer at 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.



More information about the Python-list mailing list