Perth Perth - 11 days ago 7
Python Question

Insert an array in an array using loop

I write the following code to create an array like

[[1,2,3],[2,2,3],[3,2,3]]
,

def f(X):
X[0]=X[0]+1
return X
L=[]
X=[1,2,3]
for i in range(0,3):
L=L+[X]
X=f(X)
print(L)


But it is printing
[[4, 2, 3], [4, 2, 3], [4, 2, 3]]
. Why it is happening and how to solve this using the function 'f'?

Thanks

Answer

If you have to use your function f, then try as follows:

l = []
x = [1, 2, 3]

def f(x):
    x[0] = x[0] + 1
    return x

for i in range(3):
    l.append(x[:])
    x = f(x)

Output:

>>> l
[[1, 2, 3], [2, 2, 3], [3, 2, 3]]