r/PythonLearning 5d ago

<python code>

Post image

This is python code to get student salary!

43 Upvotes

10 comments sorted by

View all comments

2

u/Potential_Fix_5007 4d ago

self.marks=[]

Is this the right way to create an empty list for an object value or is there a way to set it within the round brackets?

Im a beginner myself and so far i learned if you want to set a default value you donit within the brackets.

2

u/IdeaOverflow 4d ago

You should not initialize an empty list inside of the round brackets directly. Suppose you do it like this:

class Student:
    def __init__(self, marks=[]):
        self.marks = marks

a = Student()
b = Student()

a.marks.append(3)

print(a.marks)  # prints [3]
print(b.marks)  # prints [3]

Python will not create a new list for every new object but use the same one for each, since default arguments are evaluated at compile time. The correct way to do this would be:

class Student:
    def __init__(self, marks=None):
        self.marks = [] if marks is None else marks