scope of function parameters

Peter Pearson ppearson at nowhere.invalid
Sun May 29 13:21:11 EDT 2011


On Sun, 29 May 2011 04:30:52 -0400, Henry Olders wrote: 
[snip]
> def main():
> 	a = ['a list','with','three elements']
> 	print a
> 	print fnc1(a)
> 	print a
> 	
> def fnc1(b):
> 	return fnc2(b)
>
> def fnc2(c):
> 	c[1] = 'having'
> 	return c
>
> This is the output:
> ['a list', 'with', 'three elements']
> ['a list', 'having', 'three elements']
> ['a list', 'having', 'three elements']
>
> I had expected the third print statement to give the same
> output as the first, but variable a had been changed by
> changing variable c in fnc2.

For what it's worth, I've noticed that use of the word "variable"
is correlated with a misunderstanding of Python's way of doing
things.  

"Variable" seems to connote a box that has something in it,
so when fnc1 passes b to fnc2 which calls it c, you think
you have a box named b and a box named c, and you wonder
whether the contents of those boxes are the same or
different.

Python works in terms of objects having names, and one
object can have many names.  In your example, fnc1 works
with an object that it calls b, and which it passes to fnc2,
but fnc2 chooses to call that same object c.  The names b
and c aren't boxes that hold things, they are -- in the
words of one of this group's old hands -- sticky-note labels
that have been slapped on the same object.

-- 
To email me, substitute nowhere->spamcop, invalid->net.



More information about the Python-list mailing list