Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create an immutable list in Python? [duplicate]

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?

like image 670
user7433465 Avatar asked Jan 26 '17 13:01

user7433465


Video Answer


2 Answers

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))
like image 136
omri_saadon Avatar answered Oct 24 '22 07:10

omri_saadon


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.

like image 31
running.t Avatar answered Oct 24 '22 08:10

running.t