0

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?

3
  • Maybe you want r2.append(r1.copy()) Commented May 24, 2022 at 21:49
  • 1
    You have one list r1 which you modify several times. Appending it to r2 does 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. Commented May 24, 2022 at 21:50
  • @Mark Yes, that's a good solution. Commented May 24, 2022 at 21:52

2 Answers 2

1

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)
Sign up to request clarification or add additional context in comments.

Comments

0

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']))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.