I need to increment a single item in a list (x) and append the result to a new list (y).
This works fine on a single variable as the below example:
y = []
for x in range(100):
x = 1
print(x)
y.append(x)
print(y)
but when I try to do it within an existing list only the last iteration is being appended to the new list, example:
x = [1,2,3,4,5]
y = []
for i in range(100):
x[1] = x[1] 1
print(x)
y.append(x)
print(y)
The desired result is that the 2nd element of list y[1]
is incremented by range(100)
in the resulting list y
, like so:
[[1, 3, 3, 4, 5], [1, 4, 3, 4, 5], [1, 5, 3, 4, 5], ... [1, 101, 3, 4, 5], [1, 102, 3, 4, 5]
CodePudding user response:
You are adding the same instance of x
to the list each time, so the resulting values will all be the same.
You could add a copy of x
instead:
x = [1,2,3,4,5]
y = []
for i in range(100):
x[1] = x[1] 1
print(x)
y.append(x.copy())
print(y)
Obviously there are more efficient ways to do this, but this is a way that is easy to understand.
Output:
[[1, 3, 3, 4, 5], [1, 4, 3, 4, 5], ... [1, 100, 3, 4, 5], [1, 101, 3, 4, 5], [1, 102, 3, 4, 5]]