0

Python removes list value x from list1 as you can see below from the code :

list1 = ['a', 'b', 'c', 'c', 'a', 'x']
list2 = list1
#Remove value 'x' from list2
list2.remove('x')

#print list1
list1
['a', 'b', 'c', 'c', 'a']
shiva1791
  • 510
  • 1
  • 4
  • 11
  • TL;DR: change line #2 to `list2 = list(list1)` – Will Richardson Oct 11 '15 at 10:58
  • Thanks for the information. i have different type of list: import copy >>> list1 = [['a',1],['b',1],['c',2]] >>> list2 = copy.copy(list1) >>> list2 [['a', 1], ['b', 1], ['c', 2]] >>> list1 [['a', 1], ['b', 1], ['c', 2]] >>> list2.remove(['a',1]) >>> list1 [['a', 1], ['b', 1], ['c', 2]] >>> list2 [['b', 1], ['c', 2]] – shiva1791 Oct 11 '15 at 11:05

1 Answers1

1
`list2 = list1` it is not a copy. list2 has only references to list1. 
 Use `deepcopy`, if the list  to copy contains compound objects, 
 or use list2 = list(list1) for non compound objects.


# use deep copy if the list contains compound objects
from copy import deepcopy
list2 = deepcopy(list1)



list1 = ['a', 'b', 'c', 'c', 'a', 'x']
list2 = list1

list2 = deepcopy(list1)

list2.remove('x')

print(list1)

['a', 'b', 'c', 'c', 'a', 'x']
LetzerWille
  • 5,355
  • 4
  • 23
  • 26