Is 'everything' a refrence or isn't it?

Steven D'Aprano steve at REMOVETHIScyber.com.au
Wed Jan 4 17:15:49 EST 2006


On Wed, 04 Jan 2006 10:54:17 -0800, KraftDiner wrote:

> I was under the assumption that everything in python was a refrence...
> 
> so if I code this:
> lst = [1,2,3]
> for i in lst:
>    if i==2:
>       i = 4
> print lst
> 
> I though the contents of lst would be modified.. (After reading that
> 'everything' is a refrence.)

See, this confusion is precisely why I get the urge to slap people who
describe Python as "call by reference". It isn't.

It isn't "call by value" either -- Python never copies objects unless you
explicitly tell it to.

It is "call by object" -- you pass around *objects*. Internally, this is
quite fast, because the entire object doesn't need to be moved, only
pointers to objects, but you don't get the behaviour of either call by
reference or call by value.

In the above code, i is a name bound one at a time to the ints [1,2,3].
When you re-assign i to 4, that doesn't change the object 2 into the
object 4, because ints are immutable. Only the name i is rebound to a new
object 4. That doesn't change objects like lst which include 2 inside them. 

See this for more detail:

http://effbot.org/zone/call-by-object.htm



-- 
Steven.




More information about the Python-list mailing list