How to create and use a list of objects in Python

1 Answer

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

    def greet(self):
        return f"{self.name} is {self.age} years old."

# Create objects
person1 = Person("Albus", 98)
person2 = Person("Artemis", 81)
person3 = Person("Arthur", 109)

# Store objects in a list
people = [person1, person2, person3]


# Access individual object
print("Access individual object:")
print(people[0].greet()) 

# Iterate through the list
print("\nIterate through the list:")
for person in people:
    print(person.greet())


'''
run:
 
Access individual object:
Albus is 98 years old.

Iterate through the list:
Albus is 98 years old.
Artemis is 81 years old.
Arthur is 109 years old.
 
'''

 



answered May 29 by avibootz
...