There are several mistakes here:

First, you have inherited from "object" and there is no need to explicitly put it, you can leave it empty.

Second, the way you declared your variables in your class makes the class share the same values across all instances, thats why you get the latest modified values always. you should use "self.variable" instead, and declare a constructor function for that.

Third, you are modifying Test1.Dat1 4 times and appending the same object twice. thats why you get the same object every time.

this is the right way:

class TestDat():          # leave this empty
    def __init__(self):   # constructor function using self
        self.Dat1 = None  # variable using self.
        self.Dat2 = None  # variable using self
    
TestArray = [] #empty array

Test1 = TestDat() #this is an object
Test2 = TestDat() #this is another object
        
Test1.Dat1 = 0 #assigning value to object 1 
Test1.Dat2 = 1 #assigning value to object 1 
    
Test2.Dat1 = 3 #assigning value to object 2 
Test2.Dat2 = 4 #assigning value to object 2

TestArray.append(Test1) #append object 1
TestArray.append(Test2) #append object 2 
    
print (TestArray[0].Dat1) # this is Test1
print (TestArray[1].Dat1) # this is Test2

or even simpler:

class TestDat():
    def __init__(self, Dat1, Dat2):
        self.Dat1 = Dat1
        self.Dat2 = Dat2

TestArray = [TestDat(0,1),
             TestDat(3,4)]

print (TestArray[0].Dat1) # this is Test1
print (TestArray[1].Dat1) # this is Test2

or this way:

class TestDat():
    def __init__(self):
        self.Dat1 = None
        self.Dat2 = None
    
TestArray = [] #empty array
size = 2       #number of loops

for x in range(size):  # appending empty objects
    TestArray.append(TestDat())

#initialize later
TestArray[0].Dat1 = 0
TestArray[0].Dat2 = 1

TestArray[1].Dat1 = 3
TestArray[1].Dat2 = 4

print("print everithing")
for x in range(len(TestArray)):
    print("object "+str(x))
    print(TestArray[x].Dat1)
    print(TestArray[x].Dat2)
Answer from Carlos A. Rodriguez on Stack Overflow
Top answer
1 of 3
15

There are several mistakes here:

First, you have inherited from "object" and there is no need to explicitly put it, you can leave it empty.

Second, the way you declared your variables in your class makes the class share the same values across all instances, thats why you get the latest modified values always. you should use "self.variable" instead, and declare a constructor function for that.

Third, you are modifying Test1.Dat1 4 times and appending the same object twice. thats why you get the same object every time.

this is the right way:

class TestDat():          # leave this empty
    def __init__(self):   # constructor function using self
        self.Dat1 = None  # variable using self.
        self.Dat2 = None  # variable using self
    
TestArray = [] #empty array

Test1 = TestDat() #this is an object
Test2 = TestDat() #this is another object
        
Test1.Dat1 = 0 #assigning value to object 1 
Test1.Dat2 = 1 #assigning value to object 1 
    
Test2.Dat1 = 3 #assigning value to object 2 
Test2.Dat2 = 4 #assigning value to object 2

TestArray.append(Test1) #append object 1
TestArray.append(Test2) #append object 2 
    
print (TestArray[0].Dat1) # this is Test1
print (TestArray[1].Dat1) # this is Test2

or even simpler:

class TestDat():
    def __init__(self, Dat1, Dat2):
        self.Dat1 = Dat1
        self.Dat2 = Dat2

TestArray = [TestDat(0,1),
             TestDat(3,4)]

print (TestArray[0].Dat1) # this is Test1
print (TestArray[1].Dat1) # this is Test2

or this way:

class TestDat():
    def __init__(self):
        self.Dat1 = None
        self.Dat2 = None
    
TestArray = [] #empty array
size = 2       #number of loops

for x in range(size):  # appending empty objects
    TestArray.append(TestDat())

#initialize later
TestArray[0].Dat1 = 0
TestArray[0].Dat2 = 1

TestArray[1].Dat1 = 3
TestArray[1].Dat2 = 4

print("print everithing")
for x in range(len(TestArray)):
    print("object "+str(x))
    print(TestArray[x].Dat1)
    print(TestArray[x].Dat2)
2 of 3
0

You're right, when you add objects it does add them by reference.

There's a couple ways to do this. Probably the cleanest is just to make a new object for each entry. If you absolutely need to use the same instances with changed values, you can use copy.copy:

from copy import copy
...
# Set up object
TestArray.append(copy(test1))
# Change stuff
TestArray.append(copy(test2))

See: https://docs.python.org/2/library/copy.html for the differences between copy (aka shallow copy) and deepcopy, as it may be important depending on the complexity of your object. It also tells you how to implement __copy__ and __deepcopy__ if copying the object is nontrivial.

So, TL;DR is I'd really suggest using new objects and discourage mutability, but copy is there if you need it.

🌐
W3Schools
w3schools.com › python › python_arrays.asp
Python Arrays
Arrays are used to store multiple values in one single variable: ... An array is a special variable, which can hold more than one value at a time. If you have a list of items (a list of car names, for example), storing the cars in single variables ...
Discussions

How to Create a Python Array of Objects and Ensure Separate Instances? - TestMu AI Community
I’m trying to create a list of objects in Python. Here’s my current code: # Creating a Python object class TestDat(object): Dat1 = None Dat2 = None # Declaring the Test Array TestArray = [] # Declaring the object Test1 = TestDat() # Defining the member variables in the object Test1.Dat1 ... More on community.testmuai.com
🌐 community.testmuai.com
0
January 2, 2025
2D NumPy array of objects vs. 2D Python list efficiency
I have a 2D list a of varying shape NumPy arrays and equivalent NumPy array of objects b = np.array(a, dtype='object'). It is inconvenient to slice a, e.g. a[:][1] is not equivalent to b[:, 1], can’t be expressed by slicing and requires a list comprehension [e[1] for e in a[:]] instead. More on discuss.python.org
🌐 discuss.python.org
0
0
March 9, 2023
How to Static Type Check an array of Class Object?
There's no array type in Python, just lists: list[Book] would be the type hint. More on reddit.com
🌐 r/learnpython
3
1
November 7, 2021
Array of objects in Python - Stack Overflow
I want to define an array of objects (my defined class) of the same type in python. More on stackoverflow.com
🌐 stackoverflow.com
🌐
Python
docs.python.org › 3 › library › array.html
array — Efficient arrays of numeric values
This module defines an object type which can compactly represent an array of basic values: characters, integers, floating-point numbers. Arrays are mutable sequence types and behave very much like ...
🌐
GeeksforGeeks
geeksforgeeks.org › python › how-to-create-a-list-of-object-in-python-class
How to create a list of object in Python class - GeeksforGeeks
July 12, 2025 - List creation with extend() add multiple Geeks objects to the list a in one step. For loop iterates over the list a, printing the name and roll of each Geeks object with a space separator.
🌐
Bathgate Early Years Centre
blogs.glowscotland.org.uk › sh › ahscomputingpython › adv-higher › array-of-objects
Array of Objects – Python Cribsheets - Glow Blogs
Working with arrays of objects is very similar to working with arrays of records, but using constructors and methods instead of accessing record attributes directly.
🌐
NumPy
numpy.org › devdocs › reference › arrays.html
Array objects — NumPy v2.5.dev0 Manual
How each item in the array is to be interpreted is specified by a separate data-type object, one of which is associated with every array. In addition to basic types (integers, floats, etc.), the data type objects can also represent data structures. An item extracted from an array, e.g., by indexing, is represented by a Python object whose type is one of the array scalar types built in NumPy.
🌐
NumPy
numpy.org › doc › stable › reference › arrays.html
Array objects — NumPy v2.4 Manual
How each item in the array is to be interpreted is specified by a separate data-type object, one of which is associated with every array. In addition to basic types (integers, floats, etc.), the data type objects can also represent data structures. An item extracted from an array, e.g., by indexing, is represented by a Python object whose type is one of the array scalar types built in NumPy.
Find elsewhere
🌐
IncludeHelp
includehelp.com › python › arrays-of-objects-example.aspx
Arrays of Objects Example in Python
February 15, 2021 - Python objects are the instances of class in Python. And storing multiple objects into an array is an array of objects.
🌐
TestMu AI Community
community.testmuai.com › ask a question
How to Create a Python Array of Objects and Ensure Separate Instances? - TestMu AI Community
January 2, 2025 - Here’s my current code: # Creating a Python object class TestDat(object): Dat1 = None Dat2 = None # Declaring the Test Array TestArray = [] # Declaring the object Test1 = TestDat() # Defining the member variables in the object Test1.Dat1 ...
🌐
Python.org
discuss.python.org › python help
2D NumPy array of objects vs. 2D Python list efficiency - Python Help - Discussions on Python.org
March 9, 2023 - I have a 2D list a of varying shape NumPy arrays and equivalent NumPy array of objects b = np.array(a, dtype='object'). It is inconvenient to slice a, e.g. a[:][1] is not equivalent to b[:, 1], can’t be expressed by slicing and requires a list comprehension [e[1] for e in a[:]] instead.
🌐
GitHub
gist.github.com › ahaldane › c3f9bcf1f62d898be7c7
object array docs (future ideas) · GitHub
Object arrays are often useful for storing python string types, because it allows arbitrary string lenths (while a numpy array's string length is fixed), and because if the strings in the array are repeated python only stores a string once and ...
🌐
Linode
linode.com › docs › guides › python-arrays
Python Arrays: What They Are and How to Use Them | Linode Docs
June 17, 2022 - In Python, an array is an ordered collection of objects, all of the same type. These characteristics give arrays two main benefits. First, items in an array can be consistently identified by their index, or location, within the array.
🌐
Reddit
reddit.com › r/learnpython › how to static type check an array of class object?
r/learnpython on Reddit: How to Static Type Check an array of Class Object?
November 7, 2021 -

Say I have a class Book: somewhere and I have a function that takes in an array of Book objects as an argument. How do I Static Type check this?
I've tried

def find_max_author(book_objects: object[ ]):

🌐
DaniWeb
daniweb.com › programming › software-development › threads › 239490 › array-of-objects
python - Array of objects [SOLVED] | DaniWeb
# create a large number of spheres referencing them # with a (x, y):sphere_object dictionary pair import visual as vs spheres = {} for x in range (0, 100): for y in range (0, 100): z = 0 spheres[(x, y)] … — vegaseat 1,735 Jump to Post · Interesting, I've never used 2D arrays in Python but I would have hacked it to be useable in 'C-like' manner:
🌐
Python.org
discuss.python.org › python help
Searching Array of Data Objects - Python Help - Discussions on Python.org
May 22, 2020 - I have a data object defined: @dataclass class Blower: id_: str name: str off: bool As I create objects I place then into an array: blwr=Blower(<blah blah>) blowers.append(blwr) Now I want to search ‘blow…
🌐
Sanshaacademy
sanshaacademy.com › python › oop › arrayobjects.php
Python Array of objects
In Python, an "array of objects" usually refers to a list containing multiple instances of a class.
🌐
Python.org
discuss.python.org › python help
Instantatating an array of objects - Python Help - Discussions on Python.org
July 12, 2022 - Hello Everyone ! Actually I was instantating a array of objects like that : covergroup_names = [x for x in dir(coverage_points) if isclass(getattr(coverage_points, x))] covergroup_insts = [globals()[groupn…
🌐
Software Testing Help
softwaretestinghelp.com › home › python › python array and how to use array in python [with examples]
Python Array And How To Use Array In Python [With Examples]
April 1, 2025 - The array module in Python defines an object that is represented in an array. This object contains basic data types such as integers, floating points, and characters. Using the array module, an array can be initialized using the following syntax.
🌐
Finxter
blog.finxter.com › home › learn python blog › 5 effective ways to create numpy arrays of objects in python
5 Effective Ways to Create NumPy Arrays of Objects in Python - Be on the Right Side of Change
February 20, 2024 - NumPy’s np.array() function is a versatile workhorse for array creation. By specifying the dtype parameter as 'object', NumPy will create an array capable of holding objects, such as Python dictionaries, lists, or even custom classes.