I have looked at solutions of questions (here, here and here) that look similar but aren't. I still can't make sense of what is happening here.
class Page:
def __init__(self, l = []):
self.lines = l
def __repr__(self):
return str(self.lines)
class Line:
def __init__(self, string=None):
self.str = string
def __repr__(self):
return str(self.str)
if __name__ == '__main__':
data = [[1, 2, 3], [4, 5, 6]]
pages = []
for row in data:
page = Page()
#print(page)
#print(id(page))
for x in row:
line = Line(str(x))
page.lines.append(line)
pages.append(page)
print('Pages: ', pages)
The answer I expect is
Pages: [1, 2, 3], [4, 5, 6]
What I get instead is
Pages: [[1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 5, 6]]
I printed the page variable and see it is already populated when the outermost loop is in the second iteration. But how? Shouldn't I get a new empty object?
I am not looking for ways to fix the problem or getting my expected output, I know a few ways. I want to understand why I get this output.
Thanks!