How to loop through a list of objects in Python?

Published on Aug. 22, 2023, 12:20 p.m.

To loop through a list of objects in Python, you can use a for loop and iterate over each object in the list. Here’s an example:

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

people = [Person("John", 30), Person("Jane", 25), Person("Bob", 40)]

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

In this example, we define a Person class with a name and age property. We then create a list of Person objects and iterate over them using a for loop. Inside the loop, we access the name and age properties of each Person object and print them to the console.

Note that you can apply the same technique to loop through a list of objects of any class.

Tags: