How to create an immutable list in Python?

I am facing some problems with variables in my program. I need to save two or three versions of the list that change during the evaluation cycle. For instance:

x=[0]  
y=[0]  
while True:
        y=x  
        x[0]+=1  
        print (y,x)    
        input()

When I click Enter, it shows [1] [1]; [2] [2]; [3] [3]...But I need to save the previous state of the list in a variable:[0] [1]; [1] [2]; [2] [3] ...

What should be the code?

+4
source share
2 answers

You need to copy the value instead of the link, you can do:

y=x[:]

Instead

y = x

You can also use a copy of lib:

import copy
new_list = copy.copy(old_list)

If the list contains objects and you want to copy them as well, use a generic copy.deepcopy () instance

new_list = copy.deepcopy(old_list)

In python 3.x you can:

newlist = old_list.copy()

You can also do it in ugly mode :)

new_list = list(''.join(my_list))
+2

. , . , :

y = list(x)

y = x.

+5

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


All Articles