python arguments are post-its

Mar 30, 2007 20:39

Consider:

>>> def foo(a): a = 2
...
>>> x = 1
>>> foo(x)
>>> x
1

And:

>>> def bar(b): b.append(2)
...
>>> y = []
>>> bar(y)
>>> y
[2]

Alex Martelli dismisses newbie "by value or by reference" questions with the following:

The terminology problem may be due to the fact that, in python, the
value of a name is a reference to an object. So, you ( Read more... )

programming, code, python

Leave a comment

Comments 2

tpederson April 3 2007, 22:44:09 UTC
I think I understand it on first glance. I hope so anyway. Maybe this will confirm it: so if you would have said y = [1], then called bar(y), y would still be equal to [2] after the call, right?

Reply

dblume April 3 2007, 23:04:09 UTC
After the call, y would be [1, 2]. Is that what you meant?

It's hard to put it more correctly than Alex did. It takes a minute to read it, but once it is grokked, enlightenment is achieved.

Anyway, I thought it was cool how once I dismissed my own "reference or copy" way of thinking, I actually got it.

Reply


Leave a comment

Up