A stack is a fundamental data structure in computer science that follows the Last-In-First-Out (LIFO) principle. In Python, a stack can be implemented using a list or the collections.deque class.
A stack supports the following operations:
- Push: Adds an element to the top of the stack.
- Pop: Removes and returns the top element from the stack.
- Peek: Returns the top element from the stack without removing it.
- isEmpty: Checks if the stack is empty or not.
- Size: Returns the number of elements in the stack.
Implementing a Stack in Python
In Python, we can implement a stack using a list. Let’s see an example:
<ul> <li># Creating an empty stack</u> <li>stack = </li> </ul> # Pushing elements onto the stack stack.append(1) stack.append(2) stack.append(3) # Popping elements from the stack top_element = stack.pop() print(top_element) # Output: 3 # Peeking at the top element top_element = stack[-1] print(top_element) # Output: 2 # Checking if the stack is empty is_empty = len(stack) == 0 print(is_empty) # Output: False # Getting the size of the stack size = len(stack) print(size) # Output: 2
Using collections.deque for Stack Implementation
collections.deque class in Python provides an efficient implementation of stacks. Let’s see how to use it:
<li># Importing the deque class from the collections module</u>
<li>from collections import deque</li>
<li># Creating an empty stack</u>
<li>stack = deque()</li>
A stack is a powerful data structure that allows efficient insertion and removal of elements. In Python, you can implement a stack using a list or the
collections.dequeclass. Understanding stacks and their operations is essential for solving many computational problems.
Now that you have learned about stacks in data structures, you can start using them to solve various programming challenges efficiently.