Complete the code to add an item to the top of the stack.
stack = [] stack.[1]('apple')
To add an item to the top of a stack, we use the append method, which adds the item to the end of the list, representing the top of the stack.
Complete the code to remove the top item from the stack.
stack = ['apple', 'banana', 'cherry'] top_item = stack.[1]()
The pop() method removes and returns the last item from the list, which represents the top of the stack.
Fix the error in the code to check if the stack is empty.
stack = [] if len(stack) [1] 0: print('Stack is empty')
To check if the stack is empty, we compare the length of the stack to zero using ==. If length equals zero, the stack is empty.
Fill both blanks to create a stack with numbers 1 to 5 and remove the top item.
stack = [[1] for num in range(1, 6)] top = stack.[2]()
The list comprehension uses num to add numbers 1 to 5 to the stack. Then, pop() removes the top item.
Fill all three blanks to create a stack from letters, add 'z', and then remove the top item.
stack = [[1] for [2] in ['a', 'b', 'c']] stack.[3]('z') top = stack.pop()
The list comprehension uses letter to loop through the list. Then append adds 'z' to the top of the stack.