[issue39315] Lists of objects containing lists

Karthikeyan Singaravelan report at bugs.python.org
Sun Jan 12 13:18:54 EST 2020


Karthikeyan Singaravelan <tir.karthi at gmail.com> added the comment:

You are appending to the class attribute where both shelf[0] and shelf[1] refers to the same list as seen by output of id. You might want to create an instance variable and use it for mutating across different instances. This could help : https://docs.python.org/3/tutorial/classes.html#class-and-instance-variables


class Folder():
    papers = []

    def __init__(self):
        self.papers_self = []

shelf = []
shelf.append(Folder)
shelf.append(Folder)

print(f"{id(shelf[0]) = }")
print(f"{id(shelf[1]) = }")

shelf = []
shelf.append(Folder())
shelf.append(Folder())

print(f"{id(shelf[0].papers_self) = }")
print(f"{id(shelf[1].papers_self) = }")

shelf[0].papers_self.append("one")
shelf[1].papers_self.append("two")
print(f"{shelf[0].papers_self = }")
print(f"{shelf[1].papers_self = }")


id(shelf[0]) = 140411765635376
id(shelf[1]) = 140411765635376
id(shelf[0].papers_self) = 140411720636864
id(shelf[1].papers_self) = 140411720668608
shelf[0].papers_self = ['one']
shelf[1].papers_self = ['two']

----------
nosy: +xtreak

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue39315>
_______________________________________


More information about the Python-bugs-list mailing list