-1

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.

Simon O'Doherty
  • 9,259
  • 3
  • 26
  • 54
  • 1
    (1) you are working with lists; there is no array in your program. (2) The problem is resolved by properly appending a `copy`; it has nothing to do with the nested loop. – Prune Jun 08 '20 at 04:09
  • This appears to be simplest answer from that link (in case anyone ever goes looking for the same thing). https://stackoverflow.com/a/36452923/1167890 – Simon O'Doherty Jun 08 '20 at 04:15

1 Answers1

1

In your outer x loop, you are creating a new object with the = syntax. This loop only runs twice, so you end up with only two objects. For every run through the inner y loop, then, you are only modifying one of these first two objects.

Each time you update rec['B'], you are overwriting your previous changes to the object. When you append rec to recs, you are not creating a new object, you are just telling the list to include another reference to the same rec object.

If you print recs within your y loop instead of just rec, you can see this happen in real time.

jdaz
  • 5,964
  • 2
  • 22
  • 34