Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Increment element in a list and append to new list + python

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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]

>Solution :

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]]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading