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?