[Edu-sig] How does Python do Pointers?

David MacQuigg macquigg at ece.arizona.edu
Sun May 4 22:21:28 CEST 2008


This was the question from a student at my recent lecture to a class of engineering students studying C.  My answer was brief: It doesn't - arguments are passed by value.  Then I thought, this is really misleading for students of C, where pass-by-value means making a copy of the passed object.  So I'm looking for a simple answer that is complete, but doesn't baffle freshmen whose only experience so far is an introductory course in C.  

How about this:

'''
Python doesn't use pointers, but they really aren't needed in Python, because the way objects in memory are accessed is fundamentally different than C.  Objects in Python are "bound" to variable names.  These names are associated with pointers, but that is at a lower level not seen by the Python programmer.  If you need to get down to that level, you should be using C, not Python.
~ '''

That's a little better than my first answer, but I could elaborate with further discussion about argument passing.

'''
You know that in C there are two ways to pass a value to a function: call-by-value and call-by-reference.  Call-by-value puts a copy of the value in the function's memory area.  Call-by-reference passes to the function a pointer to the original value in the caller's memory.  In Python, passing a value to a function is done by "binding" the name of the parameter in the function to the value in the caller's memory.  This is like call-by-reference in C, but the Python programmer never sees the pointer.
~ '''

Note that Martelli says "all argument passing in Python is by value" (Python in a Nutshell, p.74), but I think this may be an error.

I would be interested in seeing how others would handle this question.

-- Dave

P.S. The lecture went very well.  The students were enthusiastic, and the Mandelbrot images were stunning!  http://ece.arizona.edu/~edatools/ece175/Lecture  The purpose of the lecture was to introduce students to higher-level programming, and show how C can still play a role when performance is critical.  I'm hoping to expand this to a 3-week sequence of lectures.




More information about the Edu-sig mailing list