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

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
Searching Array of Data Objects
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( ) blowers.append(blwr) Now I want to search ‘blowers’ for an object with a certain ‘id_’ value. I can’t seem to find how to do that. More on discuss.python.org
🌐 discuss.python.org
0
0
May 22, 2020
Python List vs Array
Arrays really aren't a thing in python. There are lists [], tuples (), and dictionaries {}. All of them can hold pretty much any data type and you can actually intermix data types. As far as strings and a csv--if it is a database like structure yes you can store data in almost any of the primary Python data structures. Throwing them into a list of lists could be one way, another would be a list of dictionaries. Using named tuples may be a really good option but that gets a little more into stuff. Pandas is also probably a good route--but again if you're asking about arrays vs. lists that is probably going beyond what you are looking for. Feel free to PM me if you need clarification. More on reddit.com
🌐 r/learnprogramming
7
3
January 24, 2019
🌐
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.
🌐
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.
🌐
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.
🌐
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.
Find elsewhere
🌐
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[ ]):

🌐
NumPy
numpy.org › doc › 2.4 › 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.
🌐
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 ...
🌐
Python documentation
docs.python.org › 3 › tutorial › datastructures.html
5. Data Structures — Python 3.14.3 documentation
A tuple consists of a number of values separated by commas, for instance: >>> t = 12345, 54321, 'hello!' >>> t[0] 12345 >>> t (12345, 54321, 'hello!') >>> # Tuples may be nested: >>> u = t, (1, 2, 3, 4, 5) >>> u ((12345, 54321, 'hello!'), (1, 2, 3, 4, 5)) >>> # Tuples are immutable: >>> t[0] = 88888 Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'tuple' object does not support item assignment >>> # but they can contain mutable objects: >>> v = ([1, 2, 3], [3, 2, 1]) >>> v ([1, 2, 3], [3, 2, 1])
🌐
Bathgate Early Years Centre
blogs.glowscotland.org.uk › sh › ahscomputingpython › adv-higher › array-of-objects
Array of Objects – Python Cribsheets
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.
🌐
DataCamp
datacamp.com › tutorial › python-arrays
Python Arrays: How to Create & Print Arrays using NumPy | DataCamp
August 8, 2024 - No, the array module is designed to hold only basic data types like integers, floats, and similar. It does not support strings or objects. For collections of these types, Python’s list or other data structures like tuples or dictionaries are more appropriate.
🌐
NumPy
numpy.org › doc › stable › reference › generated › numpy.array.html
numpy.array — NumPy v2.4 Manual
Note that any copy of the data is shallow, i.e., for arrays with object dtype, the new array will point to the same objects. See Examples for ndarray.copy. For False it raises a ValueError if a copy cannot be avoided.
🌐
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…
🌐
SciPy Lecture Notes
scipy-lectures.org › intro › numpy › array_object.html
1.4.1. The NumPy array object — Scipy lecture notes
A slicing operation creates a view on the original array, which is just a way of accessing array data. Thus the original array is not copied in memory. You can use np.may_share_memory() to check if two arrays share the same memory block.
🌐
Pandas
pandas.pydata.org › docs › user_guide › dsintro.html
Intro to data structures — pandas 3.0.1 documentation
Series is a one-dimensional labeled array capable of holding any data type (integers, strings, floating point numbers, Python objects, etc.). The axis labels are collectively referred to as the index.
🌐
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.
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › Array › from
Array.from() - JavaScript | MDN
The index of the current element being processed in the array. ... Value to use as this when executing mapFn. A new Array instance. ... To convert an ordinary object that's not iterable or array-like to an array (by enumerating its property keys, values, or both), use Object.keys(), Object.values(), or Object.entries().
🌐
CS231n
cs231n.github.io › python-numpy-tutorial
Python Numpy Tutorial (with Jupyter and Colab)
dot is available both as a function in the numpy module and as an instance method of array objects:
🌐
Python documentation
docs.python.org › 3 › reference › datamodel.html
3. Data model — Python 3.14.3 documentation
Lists are formed by placing a comma-separated list of expressions in square brackets. (Note that there are no special cases needed to form lists of length 0 or 1.) ... A bytearray object is a mutable array. They are created by the built-in ...