-1

insert mydict into mylist's third position for 4 times, where the name should increment (e.g: x1,x2,x3..)

mylist=["a","b","c","d"]
mydict={'name':"x"}

for i in range(1,5):
   mydict['name']="x"+str(i)
   mylist.insert(2,mydict)

print(mylist)

Expected output:

['a', 'b', {'name': 'x4'}, {'name': 'x3'}, {'name': 'x2'}, {'name': 'x1'}, 'c', 'd']

Actual output:

['a', 'b', {'name': 'x4'}, {'name': 'x4'}, {'name': 'x4'}, {'name': 'x4'}, 'c', 'd']

1 Answers1

0

mylist.insert(2,mydict) inserts a reference to mydict into mylist. Each iteration of the loop modifies the same dictionary object and inserts a reference to the same dictionary object. When you display the list contents at the end, you see the final contents of that dictionary. If you displayed the list within each iteration of the loop, you would see the contents changing.

Create a new dictionary on each iteration of the loop.

Dave Costa
  • 47,262
  • 8
  • 56
  • 72