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