list vs tuple

Carlos Alberto Reis Ribeiro cribeiro at mail.inet.com.br
Sat Mar 31 17:09:53 EST 2001


Ok, I'll try again. Let me try to get the problem from your point of view. 
Please, have some patience (it's always good to ask first...)

The problem that you are pointing is not with the assignment. It's about 
types, and about the difference between a pointer and the other types. 
Putting it in Pascal terms,

var a, b: ^integer;
begin
   new(a);
   /* copying the reference */
   b := a;
   /* copying the value */
   b^ := a^;
end.

As you can see, what changes is not the assignment, but the hints that you 
give to the compiler, by explicitly dereferencing the pointer when you want 
to copy the value, and not the reference.

Now let's see Python. For the sake of simplicity, I'm going to use 
analogies from Pascal, and I think I'm going to annoy the purists <wink>. 
In Python, objects are accessed always through reference. So when you do 
the assignment, you are copying the reference (or "name-binding", which 
conceptually is about the same - the difference is that we don't talk about 
explicit memory addresses).

What is missing, in your opinion, (if I got you right) is a de-reference 
operator in objects to do the copy, as for in this example:

a = [1,2,3]
b = a       # copy the reference
b^ = a^     # copy the value

Why this is not needed? There are a lot of reasons, and the experts in the 
theoretical aspects of language design may give you a full course on this. 
I can tell you about my personal experience and knowledge. The need to 
remember to reference/dereference variables is error prone. It makes code 
bigger and harder to read for no good reason. I can say to you that it's 
fairly easy to get used to Python, and it is quite effective.

In Delphi, classes are also always treated as references, and it works very 
similar to Python. Look at this example:

var p, q: TStringList;
begin
   p := TStringList.Create;
   p.Add('hello');  // in 'pure' Pascal, it should be p^.Add
   q := p;          // both p and q point to the same list
   p.Add('world');  // both lists are updated (in fact are the same)
end.

There is no need to dereference p in the "p.Add" call. But in fact, p is a 
pointer to the object, and the semantics of the assignment are just that of 
a pointer assignment. Now this is not consistent, but still is very useful, 
and somewhat easy to live with.

Also note that in Python, the constant [1,2,3] is not simply a value, but 
also a full fledged object, as it can be proved by the following snippet:

 >>> dir([1,2,3])
['append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 
'reverse', 'sort']

So when you write "[1,2,3]", you are in fact instantiating a new object.


So my dear deadmeat, I could go on this for hours on end; but I feel that 
we are going way too far trying to explain it. It's up to you now.


Carlos Ribeiro






More information about the Python-list mailing list