2

I am trying to implement a stack, then use a module called reverse_list to add something to the stack using a prebuild push module within the stack class, and then pop it out of the stack in to a list, then add it back to the stack and return it. But when i run the function it looks like the items do not get properly added to the property self.items, as the debugger shows that it forever remains at "[]", which is not a desired result, which also means it skips the other functions that require the list to be anything but empty.

my_list = [1, 2, 3, 4, 5]

class Stack:

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

    def push(self, item):
        if type(item) == list or type(item) == tuple:
            for items in item:
                self.items.append(items)
        else:
            self.items.append(item)

    def pop(self):
        self.items.pop()

    def reverse_list(self, arr):

        classer = Stack()
        classer.push(my_list)
        temp_list = []
        while self.items:
            temp_list.append(self.items.pop())
        for elements in temp_list:
            self.items.append(elements)
        return self.items


if __name__ == "__main__":
    starter = Stack()
    print(starter.reverse_list(my_list))

Current output: []

Desired output: [5, 4, 3, 2, 1]

Danke

0

1 Answer 1

4

Inside reverse_list you make another instance of Stack and you push your list onto that. But that other instance is not self, so self.items is still empty.

I think you want to get rid of classer and just use self.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.