Mark As Completed Discussion

Stacks

In computer science, a stack is an abstract data type that follows the Last-In, First-Out (LIFO) principle. Think of a stack of dishes. You can only add a new dish to the top of the stack, and you can only remove the dish that is currently on the top.

Stacks are commonly used to implement algorithms that require a last-in, first-out order. For example, function calls in a program are often stored in a stack. When a function is called, its information is pushed onto the stack, and when the function returns, its information is popped from the stack.

Here is an example of creating and manipulating a stack using a list in Python:

PYTHON
1if __name__ == '__main__':
2    # Create a stack using a list
3    stack = []
4
5    # Add elements to the stack
6    stack.append('A')
7    stack.append('B')
8    stack.append('C')
9
10    # Print the stack
11    print('Stack:', stack)
12
13    # Remove elements from the stack
14    print('Popped:', stack.pop())
15    print('Popped:', stack.pop())
16
17    # Print the stack after popping
18    print('Stack:', stack)
PYTHON
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment