In this section, we will focus on adding, removing and updating data within our data structure. These operations resemble that of database operations in CRUD (Create, Read, Update, Delete), a concept that applies not only to databases but to many aspects of software engineering. Much like how a financial application may need to add, remove or update various stocks from its inventory.
We will add three methods to our class, MyDataStructure
:
add_item: This method will take an item as an argument and append it to the end of our data list. This is similar to making a "POST" request in a web server, or inserting a new record in a database.
remove_item: This method will remove an item from our data list. It's like "DELETE" in SQL or a 'discarding' move in an AI game state tree.
update_item: This method takes an index and a new item as arguments and assigns the new item to the index in our data list. It aligns with the "UPDATE" SQL query or replacing faulty nodes in a network.
We then instantiate our class and add 'Apple' and 'Banana' to our data store. We remove 'Apple' and replace 'Banana' with 'Peach'.
After all the operations, our data store should now contain ['Peach'].
This primes us for more complex operations, like searching or sorting, that we'll cover soon, much like building knowledge of elementary statistics before jumping to machine learning models in AI.
xxxxxxxxxx
if __name__ == "__main__":
class MyDataStructure:
def __init__(self):
self.data = []
def add_item(self, item):
self.data.append(item)
def remove_item(self, item):
self.data.remove(item)
def update_item(self, index, new_item):
self.data[index] = new_item
my_struct = MyDataStructure()
my_struct.add_item('Apple')
my_struct.add_item('Banana')
my_struct.remove_item('Apple')
my_struct.update_item(0, 'Peach')
print(my_struct.data)