[Tutor] list as a first class citizen in python?

Michael P. Reilly arcege@speakeasy.net
Wed, 26 Dec 2001 12:16:40 -0500


On Wed, Dec 26, 2001 at 12:14:17PM +0530, Karthik Gurumurthy wrote:
> I found this quote on the web..regarding python...
> 
> >>>>>>>
>     Because everything is a reference, and there's no way to dereference
>     that reference, it turns out that there is no trivial way to copy
>     a list!  This fails:
> 	x = [1,2]
> 	y = x
>     Because you don't get a new list there, just a copy to an
>     old one.  Suggested work-arounds include
> 	y = x[0:]
> 	y = x[:]
> 	y = x + []
> 	y = x * 1
>     This forces people to think about references, again.
>     So much for lists being first class citizens!  Compare
>     this with Perl's
> 	@x = (1,2);
> 	@y = @x;
>     Or even with references:
> 	$x = [1,2];
> 	$y = [ @$x ];
>     or
> 	@y = @$x;
> >>>>>>>>
> 
> what's wrong with working with a reference.
> can someone explain the argument here?
> java does a similar thing. In java i would do a clone() to get a copy of an
> arraylist and in python i will
> 
> import copy
> copy.deepcopy(l)
> 
> if something is a first class citizen , should it support "copying" using
> simple assignments ? / how are first class citizens expected to behave ? :-)

Don't think of them as references, think of them as just names.  The key
here is that Python does not have variables, it has name bindings.

Perl has the advantage and the drawback that everything there is
a variable, or more exactly, a memory allocation.  In fact, the
documentation in Perl calls things "lists", which can be cast to either
a hash or an array.  As an object, there is no hash and no array, there
is only memory allocation (variables).  The references are in Perl so
you can pass around references to those variables, and to pass them back
from subroutines.

However with Python, an object is an object.. just with multiple names.
And the object is passed around and manipulated.

The article quoted is wrong in that it applies that you _must_ be able
to deference objects in Python to do things.  Python hides that you even
have a reference to an object, in the classical sense of the term.  Perl,
as you see above, has the problem that you cannot have two names to the
same object.  That you must create a reference to access the same object.

  Python:
    x = [1, 2]
    y = x  # same object
    x[0], y[0]
  Perl:
    @x = (1, 2);
    $y = \@x;  # same memory allocation
    $x[0], $$y[0];

The $y is not an array but a scalar, so now you must do something
different to access it.

My thought is that if you have a first class object, it should be that
you need to do something to copy it (either with the x[:] or x.copy()
or something similar).

After all, the U.S. Congress doesn't want cloning easily. ;)

  -Arcege