I have the following sample code:
recs = []
for x in range(1,3):
rec = {
'A': x
}
recs.append(rec)
print(rec)
for y in range(1, 3):
rec['B'] = y
recs.append(rec)
print(rec)
print('----- Array after exiting loops')
for r in recs:
print(r)
This gives this output:
{'A': 1}
{'A': 1, 'B': 1}
{'A': 1, 'B': 2}
{'A': 2}
{'A': 2, 'B': 1}
{'A': 2, 'B': 2}
----- Array after exiting loops
{'A': 1, 'B': 2}
{'A': 1, 'B': 2}
{'A': 1, 'B': 2}
{'A': 2, 'B': 2}
{'A': 2, 'B': 2}
{'A': 2, 'B': 2}
Now I can resolve it with this code:
for y in range(1, 3):
rec2 = rec.copy()
rec2['B'] = y
recs.append(rec2)
print(rec2)
What I am looking for is explaining why this behaviour occurs when you go into a nested loop.