Nelthar Nelthar - 1 month ago 17
Python Question

Why python create a pointer of one variable to another?

I was trying to resolve the following problem:


Suppose a virus that infected a university database and changed the AR
(Academic Registry) of students. After some time, it has been found
that the AR generated by the virus (ARV = x1 x2 x3 x4 x5 x6 x7 x8 x9)
the correct AR (ARC = y1 y2 y3 y4 y5 y6 y7 y8 y9) could be obtained
through the following operations:

y1 = x1, y2 = x2, y3 = x8, y4 = x7, y5 = x5, y6 = x6, y7 = x3, y8 =
x4, y9 = x9

e.g., ARV = 197845602 --> ARC = 190645782

Make a program that reads ARV and gives ARC.


My code looks like this:

pt = input('Type the AR affected by the virus: ')

arv = list(pt)
arc = arv

arc[2] = arv[7]
arc[3] = arv[6]
arc[6] = arv[2]
arc[7] = arv[3]

jarc = ''.join(arc)
print('\nCorrect AR:',jarc)


When you run the code, you see that the generated ARC its not the ARC of the example above. Why? I found it. The "arv" changes with the "arc", and it should stay immutable.

Seems to me that python create a pointer of the variable "arc" to "arv". Can anyone explain me why this happen? And how I can solve the problem correctly?

Answer

The solution is to copy the list contents, instead of the list descriptor:

arc = arv[:]

or

arc = arv.copy()

The short reason is that this is how the language is defined. You can read about the history at various Python sites; the full explanation is beyond the range of StackOverflow's general purpose.

From a high level, this is how Python implements basic pointers: object assignment is to the original object, rather than making a copy. This saves on spurious object duplication: if you want a new copy, you have to be explicit about allocating more storage.

Please note that your original, arv, is not "immutable": that is a Python technical term. A list is a mutable object; a tuple is the immutable cognate.