Skip to content Skip to sidebar Skip to footer

Pointers In Python? ` X.pointerdest = Y.pointerdest`?

I am breaking my old question to parts because it is very messy beast here. This question is related to this answer and this answer. I try to understand pointers, not sure even whe

Solution 1:

Scalar objects in Python are immutable. If you use a non-scalar object, such as a list, you can do this:

>>>x = [0]>>>y = x>>>y[0] = 4>>>y
[4]
>>>x
[4]
>>>x is y
True

Python does not have the concept of a "pointer" to a simple scalar value.

Solution 2:

Don't confuse pointers to references. They are not the same thing. A pointer is simply an address to an object. You don't really have access to the address of an object in python, only references to them.

When you assign an object to a variable, you are assigning a reference to some object to the variable.

x = 0# x is a reference to an object `0`y = [0]
# y is a reference to an object `[0]`

Some objects in python are mutable, meaning you can change properties of the object. Others are immutable, meaning you cannot change the properties of the object.

int (a scalar object) is immutable. There isn't a property of an int that you could change (aka mutating).

# suppose ints had a `value` property which stores the valuex.value = 20# does not work

list (a non-scalar object) on the other hand is mutable. You can change individual elements of the list to refer to something else.

y[0] = 20 # changes the 0th element of the list to `20`

In the examples you've shown:

>>>x = [0]>>>y = [x]

you're not dealing with pointers, you're dealing with references to lists with certain values. x is a list that contains a single integer 0. y is a list that contains a reference to whatever x refers to (in this case, the list [0]).

You can change the contents of x like so:

>>>print(x)
[0]
>>>x[0] = 2>>>print(x)
[2]

You can change the contents of the list referenced by x through y's reference:

>>> print(x)
[2]
>>> print(y)
[[2]]
>>> y[0][0] = 5
>>> print(x)
[5]
>>> print(y)
[[5]]

You can change the contents of y to reference something else:

>>>print(y)
[[5]]
>>>y[0] = 12345>>>print(x)
[5]
>>>print(y)
[12345]

It's basically the same semantics of a language such as Java or C#. You don't use pointers to objects directly (though you do indirectly since the implementations use pointers behind the scenes), but references to objects.

Post a Comment for "Pointers In Python? ` X.pointerdest = Y.pointerdest`?"