Implementing a Stack in Python: Problem with the POP function

I’m trying to implement the Stack Data Structure in Python from scratch. Unfortunately, I have a problem with the pop functionality.

The pop function should delete the top element of the stack. Unfortunately, in my implementation, running pop and then printing the array returns the same array as before the pop function.

How to better implement the pop function? I could do self.top = self.top.prev, but I am not sure if in the Stack Data Structure we have access to previous elements.

# FOLLOWS LIFO


class StackElement:
    def __init__(self, value, prev=None, next=None):
        self.value = value
        self.prev = prev # Not sure if this is available in the Stack DS...
        self.next = next


class Stack:
    def __init__(self, values):
        self.bottom = None
        self.top = None

        for v in values:
            self.push(v)

    def __str__(self):
        res = [str(x.value) for x in self]
        return " -> ".join(res)

    def __iter__(self):
        current = self.bottom
        while current:
            yield current
            current = current.next

    def __len__(self):
        res = 0
        current = self.bottom
        while current:
            res += 1
            current = current.next
        return res

    def push(self, value):
        if self.bottom is None:
            self.bottom = self.top = StackElement(value)
        else:
            self.top.next = StackElement(value)
            self.top = self.top.next
        return self.top

    def pop(self):
        if not self.is_empty():
            self.top = None
        return self.top

    def peek(self):
        if not self.is_empty():
            return self.top

    def is_empty(self):
        if len(self) != 0:
            return False
        return True


if __name__ == "__main__":
    s = Stack(["2", "3", "4"])
    print(s)
    s.push("5")
    print(s, s.top.value, s.bottom.value)
    s.pop()
    print(s, s.top, s.bottom.value)
    res = [str(x.value) for x in s]
    print(res)
    print(s)

Console Output:

2 -> 3 -> 4
2 -> 3 -> 4 -> 5 5 2
2 -> 3 -> 4 -> 5 None 2
['2', '3', '4', '5']
2 -> 3 -> 4 -> 5

New contributor

S.A.D. is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

2

I tried to simplify logic for you. Read added comments to understand. In my opinion, using .next or .previous suits to linked lists.

Code:

# FOLLOWS LIFO

class StackElement:
    def __init__(self, value): 
        self.value = value


class Stack:
    def __init__(self, values):
        self.values = [] #all values in stack
        self.top = -1 #current element index

        for v in values: 
            self.push(v) 

    def __str__(self):
        res = [str(x) for x in self.values]
        return " -> ".join(res)

    def __iter__(self):
        end = 0
        while end:
            yield self.values[end]
            end += 1

    def __len__(self):
        return len(self.values) #return list size simply

    def push(self, value):
        self.values.append(value) #assuming if there is no max size of stack, then push at the end of list
        self.top += 1 #current index + 1 as one element is added

    def pop(self):
        if not self.is_empty(): #atleast one element in stack
            self.values = self.values[:self.top] #overwrite list without the last element to follow lifo
            self.top -= 1 #current index - 1 as one element is removed

    def peek(self):
        if not self.is_empty():
            return self.values[self.top] #return last element in list

    def is_empty(self):
        if len(self.values) != 0:
            return False
        return True


if __name__ == "__main__":
    s = Stack(["2", "3", "4"])
    print(s)
    s.push("5")
    print(s, s.top)
    s.pop()
    print(s, s.top)
    res = [str(x) for x in s.values]
    print(res)
    print(s)

Output:

2 -> 3 -> 4
2 -> 3 -> 4 -> 5 3
2 -> 3 -> 4 2
['2', '3', '4']
2 -> 3 -> 4

As programmers, it is better not to overcomplicate code as it saves time and memory. Have a great day!

New contributor

Muzammil Bin Sohail is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật