0

I used the following code but it doesn't work. I got list index out of range error.

class Post:
    def __init__(self, date, reactions):
        self.date = date
        self.reactions = reactions
        self.who_reacted_name = []
    def addName(self, namex):
        self.who_reacted_name.append(namex)

Below are my variables that I want to insert them into the post_list array object. But my struggle is that I do not know how to add who_reacted_name_post1, who_reacted_name_post2 & who_reacted_name_post3 into the post_list array.

post_lists = []

date = ['2021', '2020', '2019']
reactions = ['99', '77', '34']
who_reacted_name_post1 = ['John', 'Marry', 'Franz']
who_reacted_name_post2 = ['Paul', 'Miha', 'Jad']
who_reacted_name_post3 = ['Cody', 'Marvin', 'Will']

for i in range(3):
    post_lists.append(Post(date[i],reactions[i]]))
    
    for j in range (3):
        post_lists[i].addName(who_reacted_name_post1[j]) #doesn't work
```
Klaus D.
  • 13,874
  • 5
  • 41
  • 48
Paul Viorel
  • 234
  • 1
  • 11
  • Does this answer your question? [How do I create variable variables?](https://stackoverflow.com/questions/1373164/how-do-i-create-variable-variables) – outis Sep 11 '21 at 10:15
  • Unfortunately it doesn't help me. – Paul Viorel Sep 11 '21 at 10:19
  • This code doesn't compile. It does if you remove the errant closing square bracket in `post_lists.append(Post(date[i],reactions[i]]))`. And then it works. You **must** provide a [mcve] – juanpa.arrivillaga Sep 11 '21 at 10:21

1 Answers1

1

From what I understood from your question, I hope this solution works.
I included all the individual instances of who_reacted_nameX into a nested list so it could be accessed easier.

class Post:
    def __init__(self, date, reactions):
        self.date = date
        self.reactions = reactions
        self.who_reacted_name = []
    def addName(self, namex):
        self.who_reacted_name.append(namex)

post_lists = []

date = ['2021', '2020', '2019']
reactions = ['99', '77', '34']
who_reacted_name_post = [['John', 'Marry', 'Franz'] , ['Paul', 'Miha', 'Jad'] , ['Cody', 'Marvin', 'Will']]

for i in range(3):
    post_lists.append(Post(date[i],reactions[i]))
    
for j in range (3):
    obj = post_lists[j]
    obj.addName(who_reacted_name_post[j])

for i in range(0, 3):
    obj = post_lists[i]
    print(obj.date, obj.reactions, obj.who_reacted_name)

Output

2021 99 [['John', 'Marry', 'Franz']]
2020 77 [['Paul', 'Miha', 'Jad']]
2019 34 [['Cody', 'Marvin', 'Will']]
vnk
  • 1,060
  • 1
  • 6
  • 18