How to Print a List of Class Objects in Python?

Estimated read time 1 min read

To print a list of class objects in Python, you can define a class and create a list of objects of that class. Then, you can use a for loop to iterate through the list and print the properties of each object.

Here is an example:

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

person_list = [Person("Alice", 25), Person("Bob", 30), Person("Charlie", 35)]

for person in person_list:
    print(person.name, person.age)

In this example, we define a class Person with properties name and age. We create a list of Person objects called person_list. Then, we use a for loop to iterate through the list and print the name and age properties of each object. The output will be:

Alice 25
Bob 30
Charlie 35

Note that you can customize the output format by modifying the print() statement.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply