PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, July 21, 2022

[FIXED] How to append a list to another list in a python for loop when each element of the existing list is being changed inside the for loop?

 July 21, 2022     append, extend, list, numpy, python     No comments   

Issue

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?


Solution

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)


Answered By - Telan
Answer Checked By - Candace Johnson (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing