Duplicated items in classes when use .append or .insert (Python)

Question:

I am learning Python and usually do really easy personal tasks too keep in my mind all this new language. The thing is, that I am having an issue that I don’t really know what is wrong and maybe soomeone can explain. I am a noob in all this, so maybe for sou it is so easy to see my problem, but I’ve been breaking my brain for a while and I cannot understand what is wrong.

The thing is that I am receiving duplicated values on the terminal from a list when I .instert or .append them.

The code it’s quite simple:

class Student:
    def __init__(self, name, surname, age):
        Student.name = name
        Student.surname = surname
        Student.age = age
        Student.subjects = [] # Atributo no obligatorio en forma de LIST.

student001 = Student("Mary", "Stone", 17)
student002 = Student("James", "Lincoln", 16)


student001.subjects.append("English")
student002.subjects.append("English")

print(student001.subjects)
print(student002.subjects)

student001.subjects.append("P.E.")
student002.subjects.insert(1, "P.E.")

print(student001.subjects)
print(student002.subjects)

The problem is when I print it and I receive duplicated values on the terminal:

['English', 'English']
['English', 'English']
['English', 'P.E.', 'English', 'P.E.']
['English', 'P.E.', 'English', 'P.E.']

May anyone explain me what I am doing wrong?

Thanks in advence! 🙂

I want to receive this:

['English']
['English']
['English', 'P.E.']
['English', 'P.E.']
Asked By: Lorak

||

Answers:

You are defining class attributes (shared by all instances) rather than instance attributes unique to each instance. Replace Student with self:

class Student:
    def __init__(self, name, surname, age):
        self.name = name
        self.surname = surname
        self.age = age
        self.subjects = [] # Atributo no obligatorio en forma de LIST.
Answered By: chepner
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.