0

Okay so the code below is example code i have made to illustrate my problem, i'm new to python, I'm using 2.7 and i have searched quite a lot with no success. The code all works except for one issue.

My problem is the object (Test) attribute Nested_list's that is printed at the end shows that the for loop that adds +1 to the first item in each list instead adds +1 to the first item in all 3 lists. i know the method i'm using would work on a normal list but for objects it's not quite right.

class Test(object): 
    def __init__(self):
        self.nested_lists = [[0]*10]*3

object_holder = [[]]*30

for x in xrange(0, 30):
    object_holder[x] = Test()

for objects in xrange(0, 30):
    for lists in xrange(0, 3):
        for items in xrange(0, 10):
            object_holder[objects].nested_lists[lists][items] += 1

object_holder[1].nested_lists[0][8] += 5
object_holder[1].nested_lists[2][5] += 12

print object_holder[1].nested_lists
print object_holder[1].nested_lists[0]
print object_holder[1].nested_lists[0][8]
print object_holder[1].nested_lists[2][5]

print object_holder[2].nested_lists
print object_holder[2].nested_lists[0]
print object_holder[2].nested_lists[0][8]
print object_holder[2].nested_lists[2][5]

result

[[3, 3, 3, 3, 3, 15, 3, 3, 8, 3], [3, 3, 3, 3, 3, 15, 3, 3, 8, 3], [3, 3, 3, 3, 3, 15, 3, 3, 8, 3]]

[3, 3, 3, 3, 3, 15, 3, 3, 8, 3]

8
15

[[3, 3, 3, 3, 3, 3, 3, 3, 3, 3], [3, 3, 3, 3, 3, 3, 3, 3, 3, 3], [3, 3, 3, 3, 3, 3, 3, 3, 3, 3]]

[3, 3, 3, 3, 3, 3, 3, 3, 3, 3]

3
3

why is this? When it seems I can use print to target individual list's and items?? I have looked at getattr and setattr but i cant find anything on targeting nested lists with this method.

This shows when I try to target a specific item that it is possible, but for some reason which list I target is not definable? The result I was expecting would be every item equalling 1, except the individual items I added 5 and 12 to. Any help would be greatly appreciated

  • When you multiply a list with `[foo]*3`, you don't get three independent `foo`s, you get three references to the same `foo`. There's a duplicate of this around somewhere... – Blckknght Jul 22 '17 at 23:23
  • Another post was suggested as a duplicate and it solved my issue exactly how you explained here, thanks! – Kai Forward Jul 24 '17 at 11:42

0 Answers0