This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

classification
Title: Lists of objects containing lists
Type: Stage: resolved
Components: Versions: Python 3.7
process
Status: closed Resolution: not a bug
Dependencies: Superseder:
Assigned To: Nosy List: hmathers, xtreak
Priority: normal Keywords:

Created on 2020-01-12 17:42 by hmathers, last changed 2022-04-11 14:59 by admin. This issue is now closed.

Messages (4)
msg359858 - (view) Author: (hmathers) Date: 2020-01-12 17:42
class Folder():
    papers = []

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

shelf[0].papers.append("one")
shelf[1].papers.append("two")
print(shelf[0].papers) #should just print "one" right?
msg359862 - (view) Author: Karthikeyan Singaravelan (xtreak) * (Python committer) Date: 2020-01-12 18:18
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']
msg359863 - (view) Author: (hmathers) Date: 2020-01-12 18:29
I should have known I was just doing something wrong. Thank you for your help!
msg359865 - (view) Author: Karthikeyan Singaravelan (xtreak) * (Python committer) Date: 2020-01-12 19:22
No problem, you're welcome :)
History
Date User Action Args
2022-04-11 14:59:25adminsetgithub: 83496
2020-01-12 19:22:27xtreaksetmessages: + msg359865
2020-01-12 18:29:10hmatherssetstatus: open -> closed
resolution: not a bug
messages: + msg359863

stage: resolved
2020-01-12 18:18:54xtreaksetnosy: + xtreak
messages: + msg359862
2020-01-12 17:42:08hmatherscreate