Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Double for loop giving unexpected answer

I have tested this example on both Python and JS, and since the result is the same only the former will be provided. Consider the snippet

a = []
b = []

for i in range(3):
   for j in range(2):
      a.append(0)
   print("a = ",a)

   b.append(a)
   print("b = ",b)

When done using a as a list, the result is [[0,0,0,0,0,0],[0,0,0,0,0,0],[0,0,0,0,0,0]]. If a is a string,

a = ""
b = []

for i in range(3):
   for j in range(2):
      a+= "0"
   print("a = ",a)

   b.append(a)
   print("b = ",b)

which gives ['00','0000','000000'].

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

When writing the code using lists, I was expecting the output [[0,0],[0,0,0,0],[0,0,0,0,0,0], similar to that of strings but in the shape of a list. I’ve been trying to wrap my head around this, but to no avail. What am I missing?

>Solution :

When a is a list, calling b.append(a) appends a reference to a to the end of b. Then the next time the for loop is is run, a changes and so all references to a within b also change.

Unlike lists, strings are immutable so b.append(a) appends a copy of a to the end of b. You can change your code to b.append(a[:]) to get the behavior you were looking for with strings, which makes a copy of a before appending.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading