Stack in Python
Introduction
- A stack is a data structure that allows you to store and retrieve data in a last-in, first-out (LIFO) manner. A stack is a restricted data structure because you can only insert and delete data at the top of the stack.
- A real-world example of a stack is a stack of books. You can only add a new book to the top of the stack, and you can only take a book off the top of the stack. The book at the bottom of the stack is the first book that you will take off the stack.
- In Python, a stack is represented by a list. We can create a stack by using the list method. To add an item to the top of the stack, we use the append() method. To remove an item from the top of the stack, we use the pop() method.
Syntax:
Below is the syntax used for defining the Stack in python, we can initialize a stack just like a list:
stack = [] |
Also, we can initialize a stack using deque
stack = deque() |
Functions associated with the stack are:
- empty() – This method returns whether the stack is empty or not. – Time Complexity: O(1)
- size() – This method returns the size of the stack in Time Complexity: O(1)
- top() / peek() – This method returns a reference to the topmost element of the stack in Time Complexity: O(1)
- push(a) – This method Inserts an element at the top of the stack in Time Complexity: O(1)
- pop() – This method deletes the topmost element of the stack in Time Complexity: O(1).
Implementation of stack
We can implement a Stack Using many methods The main approach we will be going to follow Is using:
- List
- deque()
Examples
Example 1: Implementing the stack using list
In this example, we will be implementing the stack using list.
stack = [] |
Output:
stack is: |
Example 2: Implementing the stack using deque()
In this example, we will be implementing the stack using deque() from collections.
from collections import deque |
Output:
stack is: |