Pop an object from a class list

I have 2 classes. AlchemicalStorage class is used to store the AlchemicalElement objects.

class AlchemicalElement:

    def __init__(self, name: str):
        self.name = name

    def __repr__(self):
        return f'<AE: {self.name}>'


class AlchemicalStorage:

    def __init__(self):
        self.storage_list = []

I already have a function that adds elements to AlchemicalStorage. What I need is a function that removes and returns previously added element from the storage by its name.

What I have so far:

def add(self, element: AlchemicalElement):
    if isinstance(element, AlchemicalElement):
        self.storage_list.append(element)
    else:
        raise TypeError()

def pop(self, element_name: str) -> AlchemicalElement or None:
    """
    Remove and return previously added element from storage by its name.

    If there are multiple elements with the same name, remove only the one that was added most recently to the
    storage. If there are no elements with the given name, do not remove anything and return None.

    :param element_name: Name of the element to remove.
    :return: The removed AlchemicalElement object or None.
    """
    self.storage_list.append(element_name)
    return self.storage_list.pop()

Obviously pop() function is incorrect. I can’t figure out what the logic is here.

An example of what I want to achieve:

storage.add(AlchemicalElement('Fire'))
storage.add(AlchemicalElement('Water'))
storage.add(AlchemicalElement('Water'))
print(storage.pop('Water') == element_three)  # True
print(storage.pop('Water') == element_two)  # True

>Solution :

You can just iterate through your storage list backwards and return the first instance, if it exists:

def pop(self, element_name: str) -> AlchemicalElement | None:
    for element in reversed(self.storage_list):
        if element.name == element_name:
            self.storage_list.remove(element)
            return element
    return None

Leave a Reply