Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List append not working

So I have something similar to this:

listPoints=[]
for x in range(100):
    for y in range(10):
        point[0]=x
        point[1]=y
        point[2] = num_cluster
        listPoints.append(point)
print listPoints

And when I print listPoints the list only contains the values of the last iteration..what I'm doing wrong? I don't see it

like image 567
user3637887 Avatar asked Aug 12 '26 17:08

user3637887


1 Answers

When you append point, you're not adding a copy of the point array -- you're adding a reference to it. So, when you do listPoints.append(point), you're essentially adding the exact same reference to the exact same thing each time. Consequently, when you change point, it appears as if every element in listPoints also changes.

You can fix the problem by creating a list instead:

listPoints=[]
for x in range(100):
    for y in range(10):
        point = [x, y, num_cluster]
        listPoints.append(point)
print listPoints

...or by copying it, if you absolutely must:

import copy

listPoints=[]
for x in range(100):
    for y in range(10):
        new_point = copy.deepcopy(point)
        new_point[0]=x
        new_point[1]=y
        new_point[2] = num_cluster
        listPoints.append(new_point)
print listPoints
like image 70
Michael0x2a Avatar answered Aug 14 '26 10:08

Michael0x2a



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!