Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,788 questions

51,694 answers

573 users

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, 2025 by avibootz
...