0

A simple problem , but have no clue about solving it

Suppose I have 2 lists , such as s and new_s : s = [[]] new_s = s I want to add new_s the same elements in s , and then add a new number to any inner list of new_s without adding to s . Like this s = [[],[22],[3]] new_s = s For i in new_s: i.append(1) Print(new_s , s) I expect the outputs to be 2 different lists (like this : [[1],[22,1],[3,1]] [[][22],[3]] ) , but they are all same .. how can I solve it ? I need a way to get rid of this small problem .

29th Jun 2021, 8:47 PM
Ali_combination
Ali_combination - avatar
4 Answers
+ 5
Sorry, just saw that you have nested lists, which means you'll need to do a deep copy, which can be done using the copy module. https://code.sololearn.com/cJk1PHb4B6nm/?ref=app
29th Jun 2021, 9:13 PM
ChaoticDawg
ChaoticDawg - avatar
+ 1
new_s = s Means that both new_s and s point to the same list. I.E. new_s is s = True You need to make a copy() of s. Then you can add and remove etc from 1 without effecting the other. new_s = s.copy()
29th Jun 2021, 9:02 PM
ChaoticDawg
ChaoticDawg - avatar
+ 1
ChaoticDawg thank you very much ChaoticDawg .
29th Jun 2021, 9:15 PM
Ali_combination
Ali_combination - avatar
0
ChaoticDawg hmmm ... but it did not work
29th Jun 2021, 9:05 PM
Ali_combination
Ali_combination - avatar