I am trying to write a code which will create modified lists in a for loop every time and append it to a new list. For this, I tried creating an empty numpy array with two elements which are to be modified inside the for loop iterating over dictionary elements.
r2 = []
r1 = np.empty(2, dtype = object)
r1 = r1.tolist()
r_1 = {'G':32,'H':3}
for i in r_1:
r1[0] = i
r1[1] = i + 'I'
print(r1)
r2.append(r1)
print(r2)
which gives me r2 as
[['H', 'HI'], ['H', 'HI']]
The r1 values in each iteration are as expected. However, I am expecting r2 to be
[['G', 'GI'], ['H', 'HI']]
I don't know why append() is not working properly. I also tried the same by doing extend() but the same thing happens on doing extend([r1]) whereas on doing extend(r1) it gives me
['G', 'GI','H', 'HI']
Am I doing it wrong or the code is interpreting something else?
r2.append(r1.copy())r1which you modify several times. Appending it tor2does not make a copy — it's still just a reference to a single list. You could move the code creating the list inside the loop to create more than one list.