[Tutor] Pointers in python ??

Michael H. Goldwasser goldwamh at slu.edu
Sun Jan 20 16:45:36 CET 2008

On Sunday January 20, 2008, Alan Gauld wrote: 

>    "Varsha Purohit" <varsha.purohit at gmail.com> wrote
>    >        Does python has concept of pointers like c/cpp ?? If yes 
>    > how.. can
>    > anyone give me a small example to how we can use pointers in python.
>    No, not really.
>    It does have the concept of C++ references however and in fact
>    thats how Pyhon variables work. They are all references. But
>    there is no real concept of a poibnter to a specific memory
>    location, and especially one that can be manipulated
>    arithmetically.

You are correct in that Python has no concept of pointer arithmetic or
any direct access of memory based on a pointer value.

However I strongly disagree with your suggestion that Python's
variables work like C++ reference variables.  The issue is that a C++
reference variable must be initially bound to an existing object and
that association cannot henceforth be changed.  Consider the following
C++ example, presuming that we have a basic Point class (not shown

Point a(0,0);
Point b(5,7);
Point& c = a;     // C++ reference variable

At this point there are two instances.  The names a and c are bound to
the same underlying instance and b is bound to a second instance.
Consider the following

c = b;       // reassigns the VALUE of c (aka a) to 5,7 but c is still bound to a
c.setX(3);   // notice that this has no effect on b;  c is not bound to b
cout << a;   // would output <3,7>
cout << b;   // would output <5,7>
cout << c;   // would output <3,7>

Translating these same seven command into Python would produce
different results, most notably because of the c=b assignment.

C++ When passing a parameter as a C++ reference, similar semantics are
used. The formal parameter is bound to the actual parameter upon
invocation of a function and from that point on assignments within the
body do not rebind the name but instead alter the value of the
underlying instance.

bool clear(Point& p) {
  p = Point(0,0);        // changes the actual parameter's value

As a final issue, notice that a C++ pointer can be assigned to null,
just as a Python variable can be assigned to None.  (C++ reference
variable cannot be null).

I should say that the SYNTAX of C++ pointers are different, as you
need to explicitly dereference them to access the underlying instance,
as in c->setX(3) rather than c.setX(3).

If you are comfortable with Java's syntax and semantics, it is easy to
explain.  The model for all data types in Python is the same as the
model used for non-primitive types in Java.

With regard,

       | Michael Goldwasser
       | Associate Professor
       | Dept. Mathematics and Computer Science
       | Saint Louis University
       | 220 North Grand Blvd.
       | St. Louis, MO 63103-2007

More information about the Tutor mailing list