How to Create a list of Objects in Python
To create a list of objects from a class in Python, define them and store them in variables by calling the class constructor. Then add the object instances as a comma-separated list inside []
(square brackets.)
class name_object(object):
def __init__(self, name):
self.name = name
object_1 = name_object('john')
object_2 = name_object('james')
object_3 = name_object('jeff')
objects = [object_1, object_2, object_3]
for obj in objects:
print(obj.name)
john
james
jeff
Add Objects to an Existing List
To add new objects to an existing list, use the list.append()
function and pass the object as the first argument.
class name_object(object):
def __init__(self, name):
self.name = name
objects = []
object_1 = name_object('john')
object_2 = name_object('james')
object_3 = name_object('jeff')
objects.append(object_1)
objects.append(object_2)
objects.append(object_3)
for obj in objects:
print(obj.name)
john
james
jeff