删除列表的功能从每个列表中删除值python

时间:2015-10-11 10:55:06

标签: python list python-3.x

Python从list1中删除列表值x,如下面的代码所示:

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']

1 个答案:

答案 0 :(得分: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']