Stack and Queue in Python
In this tutorial, we learn about Stack and Queue in Python and how do we use these and operations of stack and queue will be learned with examples.
Stack in Python
It is a linear data structure, this has a principle to follow as last in First Out(LIFO). That is it stores items in LIFO manner. This stack in Python has operations to perform like insert and delete they are called push and pop in Stack data structure. The arrangement of items will be one after the another as a bundle of papers or also we can take Undo action in editing where the last work will be undo. In stack when we add an element from one end the removing also will be done from same end by using push and pop operations.
PUSH: This operation is used to insert element into stack.
POP: This operation is used to remove element from stack.
Stack methods
Methods that used in stack are:
- push(x) – This method adds element ‘x’ at the top of the stack.
- pop() – This method deletes the topmost element of stack.
- empty()- It returns true if the stack is empty.
- size()- It returns the size of the stack.
- peek()- It returns a reference or address of the topmost element of the stack.
Example
stack = [] #using append() function #pushing elements stack.append('r') stack.append('k') print('After pushing elements:') print(stack) #poping elements print(stack.pop()) print(stack.pop()) print('\nStack after poping elements:') print(stack)
Output
After pushing elements: ['r','k'] Stack after poping elements: [] IndexError: pop from empty list
Queue in Python
It is a linear data structure of Python which stores items in FIFO(First in First Out) manner. In this type the items will be stored in a queue manner and removing of items will be done as first inserted will be removed first. Insertion and Deletion operations happens on different ends. This also has some operations.
Operations in Queue
- Enqueue – Adding items one by one into the queue is called enqueue. If the queue is full, then the queue is said as Overflow condition.
- Dequeue – Removing item from queue is called dequeue. Dequeue operation works in the order they inserted. If the queue is empty, the it is said as Underflow condition.
- Front – Getting front elemnt from the queue is called front.
- Rear – Getting last element from the queue is called rear.
Example
my_queue = [] queue.append('x') queue.append('y') queue.append('z') print("Printing my_queue:") print(my_queue) print(my_queue.pop(0))
Output
Printing my_queue: ['x','y','z'] x