[Python] Strange Behavior of pop Method in Python - implemented Stack [closed]

Discussão em 'Python' iniciado por Stack, Março 13, 2025.

  1. Stack

    Stack Membro Participativo

    I'm trying to implement a simple stack data structure in Python. Here's my code:

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

    def push(self, item):
    self.items.append(item)

    def pop(self):
    if len(self.items) == 0:
    return None
    return self.items.pop()

    def is_empty(self):
    return len(self.items) == 0

    def peek(self):
    if len(self.items) == 0:
    return None
    return self.items[-1]


    However, when I test this stack, I've encountered a strange issue. When the stack is empty, calling the pop method returns None as expected. But then, when I push an element into the stack, the pop method still seems to think the stack is empty, even though there is an element in it. For example:

    s = Stack()
    print(s.pop()) # Outputs None, as expected
    s.push(10)
    print(s.pop()) # Expected to output 10, but actually outputs None again


    I've checked the code logic, and it seems that after the pop method returns None when the stack is empty, the subsequent judgment of the stack state goes wrong. Can anyone help me point out the error in my code or provide some debugging ideas? Thanks a lot!

    I tried implementing a stack in Python with methods like push, pop, etc. I expected that when I pushed an element after popping from an initially - empty stack, the subsequent pop would return the pushed element. However, after popping from an empty stack and then pushing an element, the pop method still returned None instead of the pushed value.

    Continue reading...

Compartilhe esta Página