0

I am a newbie in python. I wrote the following code.

list1 = [{"a":"1"}, {"b":"2"}, {"c":"3 and {a}"}]
for i in range(5, 10):
    list2 = list1.copy()
    list2[-1]["c"] = list2[-1]["c"].replace("{a}", str(i))
print("List 1 is ", list1)
print("List 2 is", list2)

I expected the following to be the output

List 1 is  [{'a': '1'}, {'b': '2'}, {'c': '3 and {a}'}]
List 2 is [{'a': '1'}, {'b': '2'}, {'c': '3 and 9'}]

However the actual output is

List 1 is  [{'a': '1'}, {'b': '2'}, {'c': '3 and 5'}]
List 2 is [{'a': '1'}, {'b': '2'}, {'c': '3 and 5'}]

After some research I found out that copy() makes a shallow copy hence the actual output is what it is.

However I still don't know what change should I make in my code to get to the expected output.

I tried initialising list1 inside the for loop, the output then is

List 1 is  [{'a': '1'}, {'b': '2'}, {'c': '3 and 9'}]
List 2 is [{'a': '1'}, {'b': '2'}, {'c': '3 and 9'}]

Here as well list1 changed! What should I do?

wjandrea
  • 28,235
  • 9
  • 60
  • 81
  • 2
    You already know that a shallow copy is the problem, so the solution is a deep copy. – mkrieger1 Apr 09 '23 at 17:39
  • 2
    For one thing, you're assigning `list2` a fresh value each time through the for loop, which will throw away any changes you made in the prior loop iterations... – John Gordon Apr 09 '23 at 17:41
  • BTW, welcome to Stack Overflow! Check out the [tour], and [ask] if you want tips. – wjandrea Apr 09 '23 at 18:07

0 Answers0