Python difficulties

def myfunc(x):
 y = x
 y.append('How do I stop Python from modifying x here?')
 return y

x = []
z = myfunc(x)
print(x)
+3
source share
2 answers

You do:

y = x[:]

to make a copy of the list x.

+11
source

You need to copy X before changing it,

def myfunc(x):
 y = list(x)
 y.append('How do I stop Python from modifying x here?')
 return y

x = []
z = myfunc(x)
print(x)
+1
source

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


All Articles