0

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

Perth
  • 25
  • 4
  • 1
    Questions seeking debugging help ("why isn't this code working?") must include the desired behavior, a specific problem or error and the shortest code necessary to reproduce it in the question itself. Questions without a clear problem statement are not useful to other readers. See: [How to create a Minimal, Complete, and Verifiable example](http://stackoverflow.com/help/mcve). – barak manos Nov 28 '16 at 15:06
  • What's happening is pretty obvious, to solve just use a copy of X in f(). – polku Nov 28 '16 at 15:07
  • 1
    BTW, you may as well do `L = [[x,2,3] for x in [1,2,3]]`. – barak manos Nov 28 '16 at 15:08
  • 2
    You pass reference to same object all three times. Because of that, when You change list, it will change everywhere You used this reference. – Fejs Nov 28 '16 at 15:10
  • Can not it be solved using the function 'f'? @barak manos – Perth Nov 28 '16 at 15:11
  • It can be solved in various ways, but I don't see any point in yours. – barak manos Nov 28 '16 at 15:16
  • In another program I wrote a function that generates lists and these lists can not be simply generated like those in my question and I want to create a list of that lists. That's why I want help. @barak manos – Perth Nov 28 '16 at 15:21
  • Well, post the actual purpose, so we can relate to that. You can't seriously expect us to "twist" the answer so that it will be suitable for some other unknown purpose of yours. – barak manos Nov 28 '16 at 15:26
  • Is this a duplicate of http://stackoverflow.com/questions/2612802/how-to-clone-or-copy-a-list? – doctorlove Nov 28 '16 at 16:11

1 Answers1

0

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]]
ettanany
  • 19,038
  • 9
  • 47
  • 63