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
December 26, 2022 -

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

๐ŸŒ
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.
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ how-to-create-an-empty-class-in-python
How to create an empty class in Python?
class Student: pass # Creating ... ', st2.name, st2.age, st2.marks, st2.phone) Student 1 = Henry 17 90 Student 2 = Clark 16 77 120-6756-79 ยท Using the pass statement, we can also create empty functions and loops....
๐ŸŒ
Python Examples
pythonexamples.org โ€บ python-create-a-list-of-objects
Create a List of Objects in Python
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 - To create an empty list in Python, you can use two ways. First, the empty square bracket notation [] creates a new list object without any element in it. Second, the list() initializer method without an argument creates an empty list object too.
๐ŸŒ
Codecademy Forums
discuss.codecademy.com โ€บ frequently asked questions โ€บ python faq
How can I create an empty list? - Python FAQ - Codecademy Forums
June 12, 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.
๐ŸŒ
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?

๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ How-to-create-an-empty-list-in-Python
How to create an empty list in Python?
This is one of the simplest way to create an empty list to using square brackets[]. An empty list means the list has no elements at the time of creation, but we can add items to it later when needed. ... In Python, we have another way to create an empty list using the built-in list() constructor.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ how-to-create-an-empty-class-in-python
How to create an empty class in Python? - GeeksforGeeks
December 29, 2020 - # Python program to demonstrate # empty class class Geeks: pass # Driver's code obj = Geeks() print(obj) Output: <__main__.Geeks object at 0x02B4A340> Python also allows us to set the attributes of an object of an empty class. We can also set different attributes for different objects.
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ how-to-create-a-list-of-objects-in-the-python-class
How to create a list of objects in the Python class
In this article, we will talk about the process of creating a list of objects within a Python class. We will discuss the essential steps involved, including defining a class, creating objects of that class, adding them to a list, and performing various operations on the objects in the list.
๐ŸŒ
Flexiple
flexiple.com โ€บ python โ€บ python-initialize-list
Python Initialize List - How to do it? | Flexiple Tutorials | Python - Flexiple
The only drawback of using the * operator to initialize a list in Python is while declaring 2d arrays as it creates shallow lists i.e., only one list object would be created and all the indices would refer to this object which can be inconvenient. That is why in the case of 2d arrays, comprehensions are the better way to initialize a list. Initializing the list is one of the basic things to know while working with lists. We have discussed square brackets and the list() function ...
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.)

๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ declare-an-empty-list-in-python
Declare an Empty List in Python - GeeksforGeeks
May 1, 2025 - Declaring an empty list in Python creates a list with no elements, ready to store data dynamically.
๐ŸŒ
DNMTechs
dnmtechs.com โ€บ creating-an-empty-class-object-in-python-3
Creating an Empty Class Object in Python 3 โ€“ DNMTechs โ€“ Sharing and Storing Technology Knowledge
In the example above, we create an instance of the EmptyClass called empty_obj. We then add an attribute attribute with the value โ€œvalueโ€ and a method my_method that prints โ€œHello, world!โ€. By creating an empty class object and dynamically adding attributes and methods, you have the flexibility to customize the object based on your specific needs at runtime. In this article, we explored how to create an empty class object in Python 3.