How to add and remove objects from 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]

# Iterate through the list
print("Iterate through the list:")
for person in people:
    print(person.greet())
    
# Add a new object
people.append(Person("Dana", 27))

# Remove an object
people.pop(1) # Removes Artemis

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



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

Iterate through the list:
Albus is 98 years old.
Arthur is 109 years old.
Dana is 27 years old.
 
'''

 



answered May 29, 2025 by avibootz
...