1

origin list:

dic = {'loop': [{'date': 365, '条件': '人群行为', '类型为':'I1'}]}

origin_list = dic['loop']
# origin_list :[{'date': 365, '条件': '人群行为', '类型为':'I1'}]

then I copy origin_list to a new list:

d_copy = origin_list.copy()

change d_copy's value

d_copy[0]['date']='new value'

and origin_list also change!!,Why?

print(origin_list)
# [{'date': 'new value', '条件': '人群行为', '类型为': 'I1'}]

In another case,the origin_list doesn't change:

dd = [123]
d_copy = dd.copy()
d_copy[0]=22
print(dd) # [123]
U13-Forward
  • 69,221
  • 14
  • 89
  • 114
james
  • 643
  • 4
  • 24
  • 1
    you need to deep copy the list, otherwise the new list has the same references than the old. – Netwave May 29 '19 at 09:33
  • Also another good reference to what is happening here:https://stackoverflow.com/questions/3975376/understanding-dict-copy-shallow-or-deep – Devesh Kumar Singh May 29 '19 at 09:36
  • I don't think this is a duplicate of the other question; that one is assigning a new name to a list, i.e. `new_list = my_list`, and the answer is to use `list.copy()` instead. This question *is* using `list.copy()`, but he's still running into issues. They do mention `list.deepcopy()` in the other question's answer, but I still don't think that makes the question a duplicate. – Markus Meskanen May 29 '19 at 09:57

0 Answers0