# Stack in Python

A stack is a linear data structure that stores items in a Last-In/First-Out (LIFO) or First-In/Last-Out (FILO) manner. In stack, a new element is added at one end and an element is removed from that end only. The insert and delete operations are often called `push`

and `pop`

.

The functions associated with stack are:

**empty()**– Returns whether the stack is empty – Time Complexity : O(1)**size()**– Returns the size of the stack – Time Complexity : O(1)**top()**– Returns a reference to the top most element of the stack – Time Complexity : O(1)**push(g)**– Adds the element ‘g’ at the top of the stack – Time Complexity : O(1)**pop()**– Deletes the top most element of the stack – Time Complexity : O(1)

## Implementation

There are various ways from which a stack can be implemented in Python. This article covers the implementation of stack using data structures and modules from Python library.

Stack in Python can be implemented using following ways:

- list
- collections.deque
- queue.LifoQueue

#### Implementation using list

Python’s buil-in data structure `list`

can be used as a stack. Instead of `push(), append()`

is used to add elements to the top of stack while `pop()`

removes the element in LIFO order.

Unfortunately, list has a few shortcomings. The biggest issue is that it can run into speed issue as it grows. The items in list are stored next to each other in memory, if the stack grows bigger than the block of memory that currently hold it, then Python needs to do some memory allocations. This can lead to some `append()`

calls taking much longer than other ones.

`# Python program to ` `# demonstrate stack implementation ` `# using list ` ` ` ` ` `stack ` `=` `[] ` ` ` `# append() function to push ` `# element in the stack ` `stack.append(` `'a'` `) ` `stack.append(` `'b'` `) ` `stack.append(` `'c'` `) ` ` ` `print` `(` `'Initial stack'` `) ` `print` `(stack) ` ` ` `# pop() fucntion to pop ` `# element from stack in ` `# LIFO order ` `print` `(` `'\nElements poped from stack:'` `) ` `print` `(stack.pop()) ` `print` `(stack.pop()) ` `print` `(stack.pop()) ` ` ` `print` `(` `'\nStack after elements are poped:'` `) ` `print` `(stack) ` ` ` `# uncommenting print(stack.pop()) ` `# will cause an IndexError ` `# as the stack is now empty ` |

*chevron_right*

*filter_none*

**Output:**

Initial stack ['a', 'b', 'c'] Elements poped from stack: c b a Stack after elements are poped: []

Traceback (most recent call last): File "/home/2426bc32be6a59881fde0eec91247623.py", line 25, in <module> print(stack.pop()) IndexError: pop from empty list

#### Implementation using collections.deque

Python stack can be implemented using `deque `

class from collections module. Deque is preferred over list in the cases where we need quicker append and pop operations from both the ends of the container, as deque provides an O(1) time complexity for append and pop operations as compared to list which provides O(n) time complexity.

Same methods on deque as seen in list are used, `append()`

and `pop()`

.

`# Python program to ` `# demonstrate stack implementation ` `# using collections.deque ` ` ` ` ` `from` `collections ` `import` `deque ` ` ` `stack ` `=` `deque() ` ` ` `# append() function to push ` `# element in the stack ` `stack.append(` `'a'` `) ` `stack.append(` `'b'` `) ` `stack.append(` `'c'` `) ` ` ` `print` `(` `'Initial stack:'` `) ` `print` `(stack) ` ` ` `# pop() fucntion to pop ` `# element from stack in ` `# LIFO order ` `print` `(` `'\nElements poped from stack:'` `) ` `print` `(stack.pop()) ` `print` `(stack.pop()) ` `print` `(stack.pop()) ` ` ` `print` `(` `'\nStack after elements are poped:'` `) ` `print` `(stack) ` ` ` `# uncommenting print(stack.pop()) ` `# will cause an IndexError ` `# as the stack is now empty ` |

*chevron_right*

*filter_none*

**Output:**

Initial stack: deque(['a', 'b', 'c']) Elements poped from stack: c b a Stack after elements are poped: deque([])

Traceback (most recent call last): File "/home/97171a8f6fead6988ea96f86e4b01c32.py", line 29, in <module> print(stack.pop()) IndexError: pop from an empty deque

#### Implemenation using queue module

`Queue `

module also has a LIFO Queue, which is basically a Stack. Data is inserted into Queue using `put()`

function and `get()`

takes data out from the Queue.

There are various functions available in this module:

**maxsize**– Number of items allowed in the queue.**empty()**– Return True if the queue is empty, False otherwise.**full()**– Return True if there are maxsize items in the queue. If the queue was initialized with maxsize=0 (the default), then full() never returns True.**get()**– Remove and return an item from the queue. If queue is empty, wait until an item is available.**get_nowait()**– Return an item if one is immediately available, else raise QueueEmpty.**put(item)**– Put an item into the queue. If the queue is full, wait until a free slot is available before adding the item.**put_nowait(item)**– Put an item into the queue without blocking.**qsize()**– Return the number of items in the queue. If no free slot is immediately available, raise QueueFull.

`# Python program to ` `# demonstrate stack implementation ` `# using queue module ` ` ` ` ` `from` `queue ` `import` `LifoQueue ` ` ` `# Initializing a stack ` `stack ` `=` `LifoQueue(maxsize ` `=` `3` `) ` ` ` `# qsize() give the maxsize of ` `# the stack ` `print` `(stack.qsize()) ` ` ` `# put() function to push ` `# element in the stack ` `stack.put(` `'a'` `) ` `stack.put(` `'b'` `) ` `stack.put(` `'c'` `) ` ` ` `print` `(` `"Full: "` `, stack.full()) ` `print` `(` `"Size: "` `, stack.qsize()) ` ` ` `# get() fucntion to pop ` `# element from stack in ` `# LIFO order ` `print` `(` `'\nElements poped from the stack'` `) ` `print` `(stack.get()) ` `print` `(stack.get()) ` `print` `(stack.get()) ` ` ` `print` `(` `"\nEmpty: "` `, stack.empty()) ` |

*chevron_right*

*filter_none*

**Output:**

0 Full: True Size: 3 Elements poped from the stack c b a Empty: True

## Recommended Posts:

- numpy.stack() in Python
- Using List as Stack and Queues in Python
- Python | Stack using Doubly Linked List
- Stack Permutations (Check if an array is stack permutation of other)
- Infix to Postfix using different Precedence Values for In-Stack and Out-Stack
- Find maximum in stack in O(1) without using additional stack
- Stack | Set 3 (Reverse a string using stack)
- Sort a stack using a temporary stack
- Stack and Queue in Python using queue Module
- Spaghetti Stack
- Reverse a number using stack
- Stack Class in Java
- Stack | Set 2 (Infix to Postfix)
- How to create mergable stack?
- Rat in a Maze | Backtracking using Stack

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.