Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading