5

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?

Tagc
  • 7,701
  • 6
  • 47
  • 99
user7433465
  • 61
  • 1
  • 4

2 Answers2

6

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))
omri_saadon
  • 8,823
  • 5
  • 25
  • 53
  • In my particular case in a real program with nested lists, only deepcopy() made a difference. Like: y = deepcopy(x). – user7433465 Jan 26 '17 at 14:11
5

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.

running.t
  • 4,161
  • 2
  • 22
  • 45