The value you are defining is not an instance field for your class, its more like a static field. But python doesn't mind if you access this field from instances. So, even if you access this field from instances, it is not a different list for each instance. Basically, you are appending to the same list every time the method is called.

You'll have to do this

class A(object):

    def __init__(self):
        self.value = []

    def method(self, new_value):
        self.value.append(new_value)

Now you have a different list created for each instance.

EDIT: Let me try to explain what happens when you use a str.

class A(object):

    self.value = 'str'

    def method(self):
        self.value += '1'

That last line in the previous code is the same as this:

        self.value = self.value + '1'

Now, this makes it abit easier to see what's going on. First, python gets the value from self.value. Since there is no instance field defined yet on self, this will give 'str'. Add '1' to that and sets it to the instance field called value. This is like

self.value = 'str1'

which is the same as you'd set an instance field in the __init__ method (in my first snippet of code).

self.value = []

Does that make it clear?

Answer from sharat87 on Stack Overflow
Top answer
1 of 2
11

The value you are defining is not an instance field for your class, its more like a static field. But python doesn't mind if you access this field from instances. So, even if you access this field from instances, it is not a different list for each instance. Basically, you are appending to the same list every time the method is called.

You'll have to do this

class A(object):

    def __init__(self):
        self.value = []

    def method(self, new_value):
        self.value.append(new_value)

Now you have a different list created for each instance.

EDIT: Let me try to explain what happens when you use a str.

class A(object):

    self.value = 'str'

    def method(self):
        self.value += '1'

That last line in the previous code is the same as this:

        self.value = self.value + '1'

Now, this makes it abit easier to see what's going on. First, python gets the value from self.value. Since there is no instance field defined yet on self, this will give 'str'. Add '1' to that and sets it to the instance field called value. This is like

self.value = 'str1'

which is the same as you'd set an instance field in the __init__ method (in my first snippet of code).

self.value = []

Does that make it clear?

2 of 2
6

Define value in __init__(). There is no other way to define instance attributes.

Attributes bound outside a instance method are class attributes and shared by all instances of that class. Hence modifications of the objects bound to class attributes affect all instances of the class, as you've noticed in your example.

๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ can you create a class with an empty list attribute
r/learnpython on Reddit: Can you create a class with an empty list attribute
February 22, 2023 -

I'm trying to create texas holdem with players being class instances with hand as an attribute of type list. When I instantiate a class with no value for hand it says I need instantiate it with a list, and when I try to use self.hand = None it doesn't allow me to append new generated cards to it since it's value type none, what should I do to work around this?

Edit: Now that I'm home I can add my code for people to see

Main Code

from pokerMethods import *
from playerClass import *

def main():
    deckNumber = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"]
    deckSuit = ["Spades", "Diamonds", "Clubs", "Hearts"]
    cardList = []
    playerList = []
    p1 = Player("Herp", "Derp")
    p2 = Player("Herpy", "Derpy")

    createCard(p1, deckNumber, deckSuit, cardList)
    createCard(p2, deckNumber, deckSuit, cardList)
    
    print(p1.hand)
    print(p2.hand)
main()

Class Code:

class Player:
    def __init__(self, fname: str, lname: str, hand = [], money = 0):
        self.fname = fname
        self.lname = lname
        self.hand = hand
        self.money = money

    def addCard(self, newCard):
        self.hand.insert(0,newCard)

    def removeMoney(self, bet):
        self.money -= bet

    def addMoney(self, bet):
        self.money += bet

Method Code

import random
def createCard(player, deckNumber, deckSuit, cardList,):
    cardPlayer = deckNumber[random.randint(0, len(deckNumber)-1)] + " " + 
    deckSuit[random.randint(0, len(deckSuit)-1)]
    if cardPlayer not in cardList:
        cardList.append(cardPlayer)
        player.addCard(cardPlayer)

added hand = [] and then did self.hand = hand because when I did just self.hand = [] it gave me the error

Traceback (most recent call last):

File "Pythons Test Shit\Test'.py", line 17, in <module>

main()

File "Pythons Test Shit\Test'.py", line 9, in main

p1 = Player("Herp", "Derp")

TypeError: __init__() missing 1 required positional argument: 'hand'

and with hand = [] in the initializer

Player 1: ['2 Hearts', '1 Clubs']

Player 2: ['2 Hearts', '1 Clubs']

both instances are having their lists edited

edit 2:

re-read the comments and saw u/Binary101010 's comment, sorry for not trying that before doing all my edits and stuff but thank you so much, it worked

Discussions

Creating a list of objects in Python - Stack Overflow
I'm trying to create a Python script that opens several databases and compares their contents. In the process of creating that script, I've run into a problem in creating a list whose contents are More on stackoverflow.com
๐ŸŒ stackoverflow.com
python - how to create an list of a specific type but empty - Stack Overflow
How to create a list of a specific type of object but empty? Is it possible? I want to create an array of objects (the type is called Ghosts) which later will contain different types that inherit f... More on stackoverflow.com
๐ŸŒ stackoverflow.com
How to create a Python object that holds an empty list - Stack Overflow
Bring the best of human thought and AI automation together at your work. Explore Stack Internal ... I am a Java programmer struggling to learn Python, and almost certainly about to ask a duplicate question. In my Python code, I need to create an object that basically holds a list. When an object is instantiated, the list is to be empty. Later in the code, I want to add items: 1 #!/usr/bin/python 2 3 class ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
How can I create an empty list?
Question For this exercise, are there any other options for creating an empty list? Answer There are two ways to create an empty list in Python. The most direct way is to create a variable and assign it an empty list by using a set of square brackets ([]) containing no items. More on discuss.codecademy.com
๐ŸŒ discuss.codecademy.com
0
16
July 26, 2018
๐ŸŒ
Python Examples
pythonexamples.org โ€บ python-create-empty-list
How to Create an Empty List in Python? Examples
Python Create an Empty List Example - To create an empty list in python, assign the variable with empty square brackets. mylist = []. You can also use list class constructor. list() returns an empty list.
๐ŸŒ
Python Examples
pythonexamples.org โ€บ python-create-a-list-of-objects
Python โ€“ Create a List of Objects
We shall create objects of the Student class and add them to the list x. class Student: def __init__(self, name, age): self.name = name self.age = age # empty list x = [] student = Student('Arjun', 14) # append student object to list x.append(student) student = Student('Ajay', 15) x.append(student) student = Student('Mike', 13) x.append(student) print(x)
Top answer
1 of 5
14

Since Python 3.5 you are able to do this:
https://docs.python.org/3/library/typing.html

self.arrayOfGhosts: list[Ghost] = []

You also can import List and use the following code:

from typing import List

self.arrayOfGhosts: List[Ghost] = []
2 of 5
10

Python is a dynamic language so there is no concept of array of type.
You create an empty generic list with:

self.arrayOfGhosts = []

You don't care about the capacity of the list as it's dynamically allocated as well.
It's up to you to fill it with as many Ghost instances as you wish with:

self.arrayOfGhosts.append(Ghost())

The above is really enough, however:
If you really want to enforce this list to accept only Ghost and inheriting classes instances, you can create a custom list type like this:

class GhostList(list):

    def __init__(self, iterable=None):
        """Override initializer which can accept iterable"""
        super(GhostList, self).__init__()
        if iterable:
            for item in iterable:
                self.append(item)

    def append(self, item):
        if isinstance(item, Ghost):
            super(GhostList, self).append(item)
        else:
            raise ValueError('Ghosts allowed only')

    def insert(self, index, item):
        if isinstance(item, Ghost):
            super(GhostList, self).insert(index, item)
        else:
            raise ValueError('Ghosts allowed only')

    def __add__(self, item):
        if isinstance(item, Ghost):
            super(GhostList, self).__add__(item)
        else:
            raise ValueError('Ghosts allowed only')

    def __iadd__(self, item):
        if isinstance(item, Ghost):
            super(GhostList, self).__iadd__(item)
        else:
            raise ValueError('Ghosts allowed only')

Then for two-dimensional list you use this class like:

self.arrayOfGhosts = []
self.arrayOfGhosts.append(GhostList())
self.arrayOfGhosts[0].append(Ghost())
Find elsewhere
๐ŸŒ
Finxter
blog.finxter.com โ€บ home โ€บ learn python blog โ€บ how to create an empty list in python?
How to Create an Empty List in Python? - Be on the Right Side of Change
October 14, 2022 - Pythonโ€™s built-in list() function creates and returns a new list object. When used without an argument, it returns an empty list.
๐ŸŒ
Codecademy Forums
discuss.codecademy.com โ€บ frequently asked questions โ€บ python faq
How can I create an empty list? - Python FAQ - Codecademy Forums
July 26, 2018 - Answer There are two ways to create an empty list in Python. The most direct way is to create a variable and assign it an empty list by using a set of square brackets ([]) containing no items.
๐ŸŒ
DEV Community
dev.to โ€บ shiwani295 โ€บ how-to-create-an-empty-list-in-python-299d
How to Create an Empty List in python - DEV Community
July 9, 2022 - To create an empty list in python, assign the variable with empty square brackets. ... You can also use list class constructor as shown below to create an empty list. ... I hope you guys understand how to create empty list if like so support ...
Top answer
1 of 4
33

It is a very bad idea to use a mutable object as a default value, as you do here:

def __init__(self, lst=[], intg=0):
     # ...

Change it to this:

def __init__(self, lst=None, intg=0):
     if lst is None:
         lst = []
     # ...

The reason that your version doesn't work is that the empty list is created just once when the function is defined, not every time the function is called.

In some Python implementations you can see the value of the default values of the function by inspecting the value of func_defaults:

print test.__init__.func_defaults
name_dict[name] = test()
# ...

Output:

([],)
Anne 1 [1]
([1],)
Leo 1 [1, 2]
([1, 2],)
Suzy 1 [1, 2, 3] 
2 of 4
9

The problem lies in this line:

def __init__(self, lst=[], intg=0):

You shouldn't use a list as a default argument. The first time __init__ is called without lst specified the Python interpreter will define an empty list []. Subsequent calls to the function will operate on the same list if lst is not specified, without declaring a new list. This causes weird problems.

You should instead use a default value of None and add a check at the beginning of the function:

def __init__(self, lst=None, intg=0):
    if lst is None:
        lst = []

See this post for further details. Quoting the post:

Default arguments are evaluated at function definition time, so they're persistent across calls. This has some interesting (and confusing) side effects. An example:

>>> def foo(d=[]):
...     d.append('a')
...     return d

If you've not tried this before, you probably expect foo to always return ['a']: it should start with an empty list, append 'a' to it, and return. Here's what it actually does:

>>> foo() ['a']
>>> foo() ['a', 'a']
>>> foo() ['a', 'a', 'a']

This is because the default value for d is allocated when the function is created, not when it's called. Each time the function is called, the value is still hanging around from the last call. This gets even weirder if you throw threads into the mix. If two different threads are executing the function at the same time, and one of them changes a default argument, they both will see the change.

Of course, all of this is only true if the default argument's value is a mutable type. If we change foo to be defined as

>>> def foo2(d=0):
...     d += 1
...     return d

then it will always return 1. (The difference here is that in foo2, the variable d is being reassigned, while in foo its value was being changed.)

๐ŸŒ
Medium
medium.com โ€บ @ryan_forrester_ โ€บ how-to-create-empty-lists-in-python-d41cae5267e2
How to Create Empty Lists in Python | by ryan | Medium
October 26, 2024 - class ScoreTracker: def __init__(self, number_of_players): # Create empty score lists for each player self.scores = [[] for _ in range(number_of_players)] def add_score(self, player_id, score): if 0 <= player_id < len(self.scores): self.scores[player_id].append(score) def get_average(self, player_id): if not self.scores[player_id]: return 0 return sum(self.scores[player_id]) / len(self.scores[player_id]) # Usage game = ScoreTracker(3) # 3 players game.add_score(0, 10) game.add_score(0, 15) game.add_score(1, 20) print(f"Player 0 average: {game.get_average(0)}") # Output: 12.5 print(f"Player 1 average: {game.get_average(1)}") # Output: 20.0 print(f"Player 2 average: {game.get_average(2)}") # Output: 0.0
๐ŸŒ
Bobby Hadz
bobbyhadz.com โ€บ blog โ€บ python-create-list-of-objects
How to Create a List of Objects in Python | bobbyhadz
April 10, 2024 - Declare a new variable and initialize it to an empty list. Use a for loop to iterate over a range object. Instantiate a class to create an object on each iteration.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ how-to-create-a-list-of-object-in-python-class
How to create a list of object in Python class - GeeksforGeeks
April 15, 2025 - For loop allows you to iterate over a collection of data and append objects to a list manually. This approach gives you full control over the object creation process and is easy to understand, but itโ€™s less efficient than the previous methods, especially for larger datasets. ... class Geeks: def __init__(self, name, roll): self.name = name self.roll = roll # create list of objects a = [] for data in [('Akash', 2), ('Deependra', 40), ('Reaper', 44), ('Veer', 67)]: a.append(Geeks(data[0], data[1])) for obj in a: print(obj.name, obj.roll, sep=' ')
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ How-to-create-an-empty-list-in-Python
How to create an empty list in Python?
April 17, 2025 - The most common and efficient way to create an empty list in Python is using square brackets []. The list() constructor provides better readability, while multiplication with zero is primarily educational.
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ pass a list of empty objects to be initialized?
r/learnpython on Reddit: Pass a list of empty objects to be initialized?
February 16, 2021 -

I've spent a long time searching on how to do this and can't seem to crack it.

I have a series of objects that inherit from a parent object. The main differences between the subclasses of the parent are different model types for an ML project.

I have a couple of datasets I'd like to pass to init and run each of the models, for example, something like:

class Dtree(Supervised_Learning): 
      
      def __init__(self, features, labels): 
             super().__init__(features, labels)
             #other model init from sklearn here 


Models = [Dtree(), KNN(), Boosting(), SVM()]

def run_model(model, features, labels)

     mdl = model(features, labels)

     mdl.train()

     mdl.plot()

for model in Models:

     run_model(model)

I've tried just passing the name with out the () and then calling the class().__init___() methods with the features and labels vars, but I can't figure out how to pass the variable for self.

Anyway to do this? Or do I need to just code a function that explicitly inits all of the model objects?

๐ŸŒ
Pierian Training
pieriantraining.com โ€บ home โ€บ how to create an empty list in python
How to Create and Use an Empty List in Python
April 27, 2023 - A shallow copy creates a new object but only copies over references from the original object; in contrast, a deep copy creates entirely new objects for everything contained within the original data structure. ... Use square brackets [] instead of โ€˜list()โ€™ constructor while creating an empty list.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ how-to-create-an-empty-class-in-python
How to create an empty class in Python? - GeeksforGeeks
December 29, 2020 - File "gfg.py", line 5 ^ SyntaxError: unexpected EOF while parsing In Python, to write an empty class pass statement is used. pass is a special statement in Python that does nothing.
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ how-to-create-an-empty-class-in-python
How to create an empty class in Python?
September 15, 2022 - Empty classes in Python use the pass statement as a placeholder. They allow dynamic attribute assignment and serve as useful prototypes during development.