Euteneier
Euteneier

Reputation: 85

Modify lists defined by other lists

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

Answers (4)

Manish Jain
Manish Jain

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

dstromberg
dstromberg

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

user425495
user425495

Reputation:

Make a copy of the first list:

list2 = list(list1)

Upvotes: 0

Deelaka
Deelaka

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

Related Questions