0

Apologies if this has been answered somewhere else. I've searched stack overflow but could not find an answer to this problem.

i do not understand why list L1 is modified even after i create a temp list and put the new rows in there and assign it to list L2.

As far as i can see, i am not copying any list beside temp_list so there should be no link in memory to list L1.

Thanks in adavance

>>> L1 = []
>>> a = ['this','is','a','test','message']
>>> L1.append(a)
>>> b = ['this','is','another','good','message']
>>> L1.append(b)
>>> print (L1)
[['this', 'is', 'a', 'test', 'message'], ['this', 'is', 'another', 'good', 
'message']]
>>> list_copy_L1 = L1[:]
>>> L2 = []
>>> temp_list = []
>>> for row in list_copy_L1:
        if row[3] == 'good':
            row[3] = 'BAD'
        temp_list.append(row)
>>> L2 = temp_list[:]
>>> print (L1)
[['this', 'is', 'a', 'test', 'message'], ['this', 'is', 'another', 'BAD', 
'message']]
>>> print (L2)
[['this', 'is', 'a', 'test', 'message'], ['this', 'is', 'another', 'BAD', 
'message']]
>>> 
Lee
  • 1
  • 3
  • You are operating on a mutable object, when you assign `row[3] = 'BAD'` you are changing the sublist in `L1`. You need to create a copy before changing `row[3]`. – AChampion Jul 28 '17 at 14:30
  • `row[3] = 'BAD'` <-- the `row` is a `list` inside of your `L1` so you're affecting `L1` as well. You can verify this with `L1[0] is L2[0]`. – zwer Jul 28 '17 at 14:30
  • Thanks for your response. i created a copy of list L1, and iterating through the copy instead. The result is still the same with list L1 being modified. – Lee Jul 28 '17 at 14:55
  • It's plodding but one way around it is build a new row. if row[3] == 'good': new_row=[row[0],row[1],row[2],'BAD',row[4]] temp_list.append(new_row) else: temp_list.append(row) – Rolf of Saxony Jul 28 '17 at 15:24
  • list_copy_L1 = deepcopy(L1) instead of list_copy_L1 = L1[:] solved the issue, Thanks! – Lee Jul 31 '17 at 08:00

0 Answers0