Python – Create a List of Objects

Create a list of objects

To create a list of objects in Python, you can create an empty list and add the objects to the list, or just initialise the list with objects.

Examples

1. Create empty list and add objects

In the following program we define a class Student, and take an empty list x. We shall create objects of the Student class and add them to the list x.

Python Program

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)
Run

Output

[<__main__.Student object at 0x104603c10>, <__main__.Student object at 0x10475bb80>, <__main__.Student object at 0x10475bb20>]

2. Initialize list with objects

In the following program we create a list x initialised with Student elements.

Python Program

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

#student objects
student1 = Student('Arjun', 14)
student2 = Student('Ajay', 15)
student3 = Student('Mike', 13)

#create list with objects
x = [student1, student2, student3]

print(x)
Run

Output

[<__main__.Student object at 0x1044a3c10>, <__main__.Student object at 0x1044a3bb0>, <__main__.Student object at 0x1044a3b50>]

Summary

In this tutorial of Python Examples, we learned how to create a list of objects, with the help of examples.