I'm facing some problems with variables in my program. I need to keep two or three versions of a list that changes during loop evaluation. For example:
x=[0]
y=[0]
while True:
y=x
x[0]+=1
print (y,x)
input()
As I press Enter it shows [1] [1]; [2] [2]; [3] [3]...
But I need to keep the previous state of the list in a variable: [0] [1]; [1] [2]; [2] [3] ...
What should the code be?
You need to copy the value instead of the reference, you can do:
y=x[:]
Instead
y = x
You also can use the copy lib:
import copy
new_list = copy.copy(old_list)
If the list contains objects and you want to copy them as well, use generic copy.deepcopy()
new_list = copy.deepcopy(old_list)
In python 3.x you can do:
newlist = old_list.copy()
You can do it in the ugly mode as well :)
new_list = list(''.join(my_list))
Actually you don't need an immutable list. What you really need is creating real copy of list instead of just copying references. So I think the answer to your issue is:
y = list(x)
Instead of y = x
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With