How to Create a List of Class Instances in Python?

Estimated read time 2 min read

To create a list of class instances in Python, you can define a class, create instances of that class, and add them to a list. Here’s an example code that creates a class named Person, creates instances of that class, and adds them to a list:

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

    def __str__(self):
        return f"{self.name} ({self.age})"

# create instances of the Person class
person1 = Person("John", 30)
person2 = Person("Alice", 25)
person3 = Person("Bob", 40)

# add the instances to a list
people = [person1, person2, person3]

# print the list of instances
for person in people:
    print(person)

In this example, we define a class Person with a constructor that takes a name and an age argument. The __str__() method is defined to return a string representation of a Person instance.

Next, we create three instances of the Person class, person1, person2, and person3, with different values for their name and age attributes.

Finally, we create a list people that contains these instances as separate elements, and use a for loop to print each instance using the print() function.

Note that you can modify the Person class to include more attributes or methods, and you can also modify the people list to add or remove instances as needed.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply