assigning values in python and perl

George Sakkis george.sakkis at
Thu Jan 17 06:27:16 CET 2008

On Jan 16, 10:34 pm, "J. Peng" <peng.... at> wrote:

> I just thought python's way of assigning value to a variable is really
> different to other language like C,perl. :)
> Below two ways (python and perl) are called "pass by reference", but
> they get different results.
> (snipped)

Python's parameter passing is like passing a pointer in C/C++. You can
modify the object that is pointed by the pointer (if the object is
mutable), but reassigning the pointer (i.e. making it point to
something else) has no effect outside the function. Consider the
following programs in Python and C:

#==== Python version ====================
def test(x):
  y = [4,5,6]
  # modifies the passed object
  x[0] = -x[0];
  # rebinds the name x to the object referenced by y; no effect on
passed object
  x = y

x = [1,2,3]
print x

$ python
[-1, 2, 3]

#==== C version ====================

#include <stdio.h>

void test(int x[]) {
   int y[] = {4,5,6};
   // modifies the passed array
   x[0] = -x[0];
   // reassigns the pointer to the local array pointed by y; no effect
on passed array
   x = y;

int main(int argc, char* argv[]) {
   int x[] = {1,2,3};
   for (int i=0; i<3; i++) {
     printf("%d ", x[i]);

$ gcc -std=c99 test.c
$ ./a.out
-1 2 3

Hope this helps,

More information about the Python-list mailing list