x = 0
y = []
for i in range (5):
y.append(x)
x+=1
print y
Gives:
[0, 1, 2, 3, 4]
But,
x = range (2)
y = []
for i in range (5):
y.append(x)
x[0]+=1
print y
I would have thought (hoped) that this gives me:
[[0, 1], [1, 1], [2, 1], [3, 1], [4, 1]]
But instead it just gives me:
[[5, 1], [5, 1], [5, 1], [5, 1], [5, 1]]
I've tested it by putting 'print y' inside the for loop, and obviously what is happening is that when x[0]+=1, all the 'x's that are already inside 'y' are being updated with the new value.
How do I write the program so that it 'forgets' that the 'x's already in list 'y' are still variables (and so doesn't keep updating them)?
I've realized I could just write this one specifically as:
y = []
for i in range (5):
x = [i, 1]
y.append(x)
But what if I wanted to define x outside of the for loop? I can't think of a time when I would want to do it this way but I just want to know anyway.
ywith multiple references to the same list. To fix it, copy;y.append(x[:]).