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?
CodePudding user response:
When you append r1
twice to r2
it essentially makes r2
a list of [r1, r1]
not the contents of r1
when it was appended, so when r1
is changed before the second append, the first element in r2
which is a reference to r1
is also changed.
One solution is to not use r1 at all and just append the contents directly:
r2 = []
r_1 = {'G':32,'H':3}
for i in r_1:
r2.append([i, i "I"])
print(r2)
A second solution is to append a copy of r1 to avoid the two elements having the same reference:
r2 = []
r_1 = {'G':32,'H':3}
r1 = [None, None]
for i in r_1:
r1[0] = i
r1[1] = i "I"
r2.append(r1.copy())
print(r2)
CodePudding user response:
I think that the problem lies with the fact that you pass a pointer of r1 to r2. r1 is created outside the scope of the for loop but is changed inside the for loop. So, what r2 sees is 2 instances of r1 at its last state, which is ['H', 'HI'].
Try passing the subarray directly to r2 like r2.append([i, i 'I'])
If you need a numpy array in r2, you can do r2.append(np.array([i, i 'I']))