[Tutor] list method help

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Fri Feb 3 23:33:25 CET 2006


> > But this assignment sort of puzzles me to why it's done like this
> > (maybe cuz I am not used to it and can not see beyond my own
> > experience in coding (having a blind spot or something like that)).


If we have a snippet of code like:

###########
def test():
    x = []
    f(x)
    print x
###########

we have a strong guarantee that 'x' won't be redirected to another value.
The situation above, right before calling f(), looks like:

   x --------------> []

Of course, f() can apply mutation on the list and change the shape of the
list value.  But no matter what, f can't get 'x' directed to an entirely
different list value.


In Python, all names are just arrows to values.  Assignment is the
operation of getting the target on the left hand side to direct its arrow
at the value on the right hand side.  Variable name lookup is just getting
at the value that the arrow is pointing at.

If we're familiar with a language like C, we can imagine that, in Python's
world, all variable names are pointers to things.  So when we see
something like:

######
x = 42
######

if we were to literally translate what Python's does here in a C context,
we'd see something like this:

/******/
int *x = make_int(42);
/******/

where there's a core set of value-making functions available somewhere,
like:

/******/
int* make_int(int val) {
    int *result = malloc(sizeof(int));
    *result = val;
    return result;
/******/


> Good idea. Just get over it, it's really not a big deal. ;-) It's only a
> problem if you try to hold on to the copying model, then you will be
> occasionally surprised.

The copying model works just as well, so long as we keep in mind that
variable names hold arrows (where those arrows aim at values) rather than
the values themselves.


Best of wishes!



More information about the Tutor mailing list