Reputation: 85
I am trying to make a game but cant figure out how to modify the list without affecting another one. My code is
list1 = [1,2,3,4,5,6,7,8,9,0]
list2 = list1
for i in range(len(list2)):
list2.remove(i)
print (list1)
print (list2)
and the result is
[]
[]
How can i make it so the two are not connected (I need to combine lists but there removed once the program restarts)
Upvotes: 4
Views: 85
Reputation: 869
You can use the copy module
list1 = [1,2,3,4,5,6,7,8,9,0]
import copy
list2 = copy.copy(list1)
Any change in the list1 will not effect list2 and vice versa. If your list is a compound list i.e. contains list as elements, you need to use deepcopy as follows:
list2 = copy.deepcopy(list1)
For more use cases see http://docs.python.org/2/library/copy.html
Upvotes: 1
Reputation: 7177
This is good:
list2 = list(list1)
Or here's the way I usually do it:
list2 = list1[:]
The first is using the list constructor. The second is using a slice. I haven't bothered to check which is faster.
Upvotes: 0
Reputation: 13693
You can make list2
a new object:
list2 = list(list1)
So the output would be:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
[]
Upvotes: 3