How to assign by value in python

I understand that because of how Python works x = []; y = x; x.append(1); y, it will print [1]. However, on the contrary,

z = [1,2]
temp = z
temp[1] = 3
z,temp

will print ([1,3],[1,3]). If I understand correctly, the two zand temppoint to the same list, so changes to one will change the other, because the lists are subject to change. How can I prevent this? Namely, I want to create a for loop that will copy zto temp, change it differently, and push it into the queue. For this, it zshould always contain a base array, so I need the shift to tempnot change z.

EDIT: I tried changing z to a tuple so z=z,that by typing z[0]instead z. However, this does not solve my problem.

+1
source share
2 answers

Copying a list is easy ... Just slice it:

temp = z[:]

This will create small copies - mutations to elements in the list will appear in elements in z, but will not directly change to temp.


For more general purposes, python has a module copythat you can use:

temp = copy.copy(z)

Or perhaps:

temp = copy.deepcopy(z)
+7
source

Why not make a tempcopy z:

>>> z = [1, 2]
>>> temp = z[:]
>>> temp[1] = 3
>>> z
[1, 2]
>>> temp
[1, 3]
>>>

[:] easily makes a shallow copy of the list.

However, you may be interested in copy.copyand copy.deepcopy, both of which are based on the Python module copy.

+4
source

Source: https://habr.com/ru/post/1678830/


All Articles