Skip to content

Python Create List of Objects

  • by

To Create a List of Objects first create one empty list and then append multiple class objects to this list in Python. Python list can hold a list of class objects.

You can access any member of that object like method or variables. The syntax for the append method is as follows:

list.append(obj)

Python Create List of Objects Example

A simple example code creates an empty list and adds objects for the same class instance.

class Student:
def __init__(self, name, age):
self.name = name
self.age = age


sList = []
sList.append(Student("John", 20))
sList.append(Student("Pink", 30))
sList.append(Student("Tim", 40))

print(sList)

for student in sList:
print('Name : {}, Age : {}'.format(student.name, student.age))

Output:

Python Create List of Objects

Initialize list with objects

class Student:
def __init__(self, name, age):
self.name = name
self.age = age


# student objects
s1 = Student('Arjun', 20)
s2 = Student('Ajay', 30)
s3 = Student('Mike', 40)

# create list with objects
x = [s1, s2, s3]

print(x)

Output:

[<__main__.Student object at 0x0000022F1EC03B80>, 
<__main__.Student object at 0x0000022F1EC03B20>, 
<__main__.Student object at 0x0000022F1EC03AC0>]

Do comment if you have any doubts or suggestions on this Python object topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading