Preferred method for "Assignment by value"

sturlamolden sturlamolden at yahoo.no
Tue Apr 15 16:49:15 EDT 2008


On Apr 15, 7:23 pm, hall.j... at gmail.com wrote:


> test = [[1],[2]]
> x = test[0]

Python names are pointer to values. Python behaves like Lisp - not
like Visual Basic or C#.

Here you make x point to the object which is currently pointed to by
the first element in the list test. If you now reassign test[0] = [2],
x is still pointing to [1].


> x[0] = 5
> test>>> [[5],[2]]
>
> x = 1

Here you reassign x to point to an int object vith value 1. In other
words, x is no longer pointing to the same object as the first element
in the list test.

That is why get this:

> test
>
> >>>[[5],[2]]
> x
> >>> 1


> test = [[1,2],[3,4]]
> I need to do some data manipulation with the first list in the above
> list without changing <test>
> obviously x = test[0] will not work as any changes i make will alter
> the original...

You make a slice, e.g.

x = [from:until:stride]

Now x is pointing to a new list object, containing a subset of the
elements in list. If you reassign elements in x, test will still be
the same.

The point to remember, is that a list does not contain values, but
pointers to values. This can be very different from arrays in C, VB,
Java or C#:

a = [1,2,3,4,5] in Python

is different from

int a[] = {1,2,3,4,5};

The Python statement makes a list of five pointers, each pointing to
an immutable int object on the heap. The C statement allocates a
buffer of 5 ints on the stack.

If you can read C, the Python statement a = [1,2,3,4,5] is thus
similar to something like

int **a, i, amortize_padding=4;
a = malloc(5 * sizeof(int*) + amortize_padding*sizeof(int*));
for (i=0; i<5; i++) {
   a[i] = malloc(sizeof(int));
   *a[i] = i;
}




























More information about the Python-list mailing list