0% found this document useful (0 votes)
7 views13 pages

Stack in Python - GeeksforGeeks

The document provides an overview of stacks in Python, explaining their Last-In/First-Out (LIFO) structure and associated operations such as push and pop. It details various implementations of stacks using Python's built-in list, collections.deque, queue.LifoQueue, and singly linked lists, highlighting their advantages and drawbacks. Additionally, it discusses the time complexity of stack operations and practical applications of stacks in programming.

Uploaded by

yangui rania
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views13 pages

Stack in Python - GeeksforGeeks

The document provides an overview of stacks in Python, explaining their Last-In/First-Out (LIFO) structure and associated operations such as push and pop. It details various implementations of stacks using Python's built-in list, collections.deque, queue.LifoQueue, and singly linked lists, highlighting their advantages and drawbacks. Additionally, it discusses the time complexity of stack operations and practical applications of stacks in programming.

Uploaded by

yangui rania
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

15/03/2024 05:47 Stack in Python - GeeksforGeeks

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)
Free Python 3 Tutorial Data Types Control Flow Functions List String Set Tuple Dictionary Oops
top() / peek() – Returns a reference to the topmost element of the stack –
Time Complexity: O(1)
push(a) – Inserts the element ‘a’ at the top of the stack – Time Complexity:
O(1)
pop() – Deletes the topmost 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 a stack using data structures and modules
from the Python library.
Stack in Python can be implemented using the following ways:

We use cookies to ensure you have the best browsing experience on our website. By using our
Got It !
site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy

https://www.geeksforgeeks.org/stack-in-python/ 1/13
15/03/2024 05:47 Stack in Python - GeeksforGeeks

list
Collections.deque
queue.LifoQueue

Implementation using list:

Python’s built-in data structure list can be used as a stack. Instead of push(),
append() is used to add elements to the top of the stack while pop() removes
the element in LIFO order.
Unfortunately, the list has a few shortcomings. The biggest issue is that it can
run into speed issues as it grows. The items in the list are stored next to each
other in memory, if the stack grows bigger than the block of memory that
currently holds it, then Python needs to do some memory allocations. This can
lead to some append() calls taking much longer than other ones.

Python3

# Python program to
# demonstrate stack implementation
# using list

stack = []
We use cookies to ensure you have the best browsing experience on our website. By using our
site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
# append() function to push

https://www.geeksforgeeks.org/stack-in-python/ 2/13
15/03/2024 05:47 Stack in Python - GeeksforGeeks

# element in the stack


stack.append('a')
stack.append('b')
stack.append('c')

print('Initial stack')
print(stack)

# pop() function to pop


# element from stack in
# LIFO order
print('\nElements popped from stack:')
print(stack.pop())
print(stack.pop())
print(stack.pop())

print('\nStack after elements are popped:')


print(stack)

# uncommenting print(stack.pop())
# will cause an IndexError
# as the stack is now empty

Output

Initial stack
['a', 'b', 'c']

Elements popped from stack:


c
b
a

Stack after elements are popped:


[]

Implementation using collections.deque:

Python stack can be implemented using the deque class from the collections
module. Deque is preferred over the 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
tocookies
We use list which provides
to ensure O(n)
you have the time complexity.
best browsing experience on our website. By using our
site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy

https://www.geeksforgeeks.org/stack-in-python/ 3/13
15/03/2024 05:47 Stack in Python - GeeksforGeeks

The same methods on deque as seen in the list are used, append() and pop().

Python3

# 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() function to pop


# element from stack in
# LIFO order
print('\nElements popped from stack:')
print(stack.pop())
print(stack.pop())
print(stack.pop())

print('\nStack after elements are popped:')


print(stack)

# uncommenting print(stack.pop())
# will cause an IndexError
# as the stack is now empty

Output

Initial stack:
deque(['a', 'b', 'c'])

Elements popped from stack:


c
b
We useacookies to ensure you have the best browsing experience on our website. By using our
site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy

https://www.geeksforgeeks.org/stack-in-python/ 4/13
15/03/2024 05:47 Stack in Python - GeeksforGeeks

Stack after elements are popped:


deque([])

Implementation using queue module

Queue module also has a LIFO Queue, which is basically a Stack. Data is
inserted into Queue using the 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 the 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. If no free
slot is immediately available, raise QueueFull.
qsize() – Return the number of items in the queue.

Python3

# Python program to
# demonstrate stack implementation
# using queue module

from queue import LifoQueue

# Initializing a stack
stack = LifoQueue(maxsize=3)

# qsize() show the number of elements


# in the stack
print(stack.qsize())

# put() function to push


# element in the stack
We usestack.put('a')
cookies to ensure you have the best browsing experience on our website. By using our
site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
stack.put('b')

https://www.geeksforgeeks.org/stack-in-python/ 5/13
15/03/2024 05:47 Stack in Python - GeeksforGeeks

stack.put('c')

print("Full: ", stack.full())


print("Size: ", stack.qsize())

# get() function to pop


# element from stack in
# LIFO order
print('\nElements popped from the stack')
print(stack.get())
print(stack.get())
print(stack.get())

print("\nEmpty: ", stack.empty())

Output

0
Full: True
Size: 3

Elements popped from the stack


c
b
a

Empty: True

Implementation using a singly linked list:

The linked list has two methods addHead(item) and removeHead() that run in
constant time. These two methods are suitable to implement a stack.

getSize()– Get the number of items in the stack.


isEmpty() – Return True if the stack is empty, False otherwise.
peek() – Return the top item in the stack. If the stack is empty, raise an
exception.
push(value) – Push a value into the head of the stack.
pop() – Remove and return a value in the head of the stack. If the stack is
empty, raise an exception.

We use cookiesis
Below to ensure you have the best browsing
the implementation experience
of the above on our website. By using our
approach:
site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy

https://www.geeksforgeeks.org/stack-in-python/ 6/13
15/03/2024 05:47 Stack in Python - GeeksforGeeks

Python3

# Python program to demonstrate


# stack implementation using a linked list.
# node class

class Node:
def __init__(self, value):
self.value = value
self.next = None

class Stack:

# Initializing a stack.
# Use a dummy node, which is
# easier for handling edge cases.
def __init__(self):
self.head = Node("head")
self.size = 0

# String representation of the stack


def __str__(self):
cur = self.head.next
out = ""
while cur:
out += str(cur.value) + "->"
cur = cur.next
return out[:-2]

# Get the current size of the stack


def getSize(self):
return self.size

# Check if the stack is empty


def isEmpty(self):
return self.size == 0

# Get the top item of the stack


def peek(self):

# Sanitary check to see if we


# are peeking an empty stack.
if self.isEmpty():
raise Exception("Peeking from an empty stack")
return self.head.next.value

# Push a value into the stack.


def push(self, value):
node = Node(value)
node.next = self.head.next
We use cookies toself.head.next
ensure you have the=best browsing experience on our website. By using our
node
site, you acknowledge that you+=
self.size have1 read and understood our Cookie Policy & Privacy Policy

https://www.geeksforgeeks.org/stack-in-python/ 7/13
15/03/2024 05:47 Stack in Python - GeeksforGeeks

# Remove a value from the stack and return.


def pop(self):
if self.isEmpty():
raise Exception("Popping from an empty stack")
remove = self.head.next
self.head.next = self.head.next.next
self.size -= 1
return remove.value

# Driver Code
if __name__ == "__main__":
stack = Stack()
for i in range(1, 11):
stack.push(i)
print(f"Stack: {stack}")

for _ in range(1, 6):


remove = stack.pop()
print(f"Pop: {remove}")
print(f"Stack: {stack}")

Output

Stack: 10->9->8->7->6->5->4->3->2->1
Pop: 10
Pop: 9
Pop: 8
Pop: 7
Pop: 6
Stack: 5->4->3->2->1

Advantages of Stack:

Stacks are simple data structures with a well-defined set of operations,


which makes them easy to understand and use.
Stacks are efficient for adding and removing elements, as these operations
have a time complexity of O(1).
In order to reverse the order of elements we use the stack data structure.
Stacks can be used to implement undo/redo functions in applications.

Drawbacks of Stack:
We use cookies to ensure you have the best browsing experience on our website. By using our
site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy

https://www.geeksforgeeks.org/stack-in-python/ 8/13
15/03/2024 05:47 Stack in Python - GeeksforGeeks

Restriction of size in Stack is a drawback and if they are full, you cannot add
any more elements to the stack.
Stacks do not provide fast access to elements other than the top element.
Stacks do not support efficient searching, as you have to pop elements one
by one until you find the element you are looking for.

Don't miss your chance to ride the wave of the data revolution! Every industry is
scaling new heights by tapping into the power of data. Sharpen your skills and
become a part of the hottest trend in the 21st century.

Dive into the future of technology - explore the Complete Machine Learning and
Data Science Program by GeeksforGeeks and stay ahead of the curve.

Last Updated : 09 Mar, 2023 172

Previous Next

Stack Class in Java C# Stack with Examples

Share your thoughts in the comments Add Your Comment

Similar Reads
Stack and Queue in Python using queue Python Program to Reverse the Content
Module of a File using Stack

numpy.stack() in Python Python | Stack using Doubly Linked List

How are variables stored in Python - Python - Stack and StackSwitcher in


Stack or Heap? GTK+ 3

How to print exception stack trace in


We use cookies to ensure you have the best browsing experience on Python program
our website. to our
By using reverse a stack
Python?
site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy

https://www.geeksforgeeks.org/stack-in-python/ 9/13
15/03/2024 05:47 Stack in Python - GeeksforGeeks

Python Program To Check For Balanced


Python PyTorch stack() method Brackets In An Expression (Well-
Formedness) Using Stack

N nikhilagg… Follow

Article Tags : Python-Data-Structures , Python


Practice Tags : python

Additional Information

A-143, 9th Floor, Sovereign Corporate


Tower, Sector-136, Noida, Uttar Pradesh -
201305

Company Explore
About Us Hack-A-Thons
Legal GfG Weekly Contest
Careers DSA in JAVA/C++
In Media Master System Design
We use cookies to ensure you have the best browsing experience on our website. By using our
site, you acknowledge thatContact Usread and understood our Cookie Policy & Privacy PolicyMaster CP
you have

https://www.geeksforgeeks.org/stack-in-python/ 10/13
15/03/2024 05:47 Stack in Python - GeeksforGeeks

Advertise with us GeeksforGeeks Videos


GFG Corporate Solution Geeks Community
Placement Training Program

Languages DSA
Python Data Structures
Java Algorithms
C++ DSA for Beginners
PHP Basic DSA Problems
GoLang DSA Roadmap
SQL Top 100 DSA Interview Problems
R Language DSA Roadmap by Sandeep Jain
Android Tutorial All Cheat Sheets
Tutorials Archive

Data Science & ML HTML & CSS


Data Science With Python HTML
Data Science For Beginner CSS
Machine Learning Tutorial Web Templates
ML Maths CSS Frameworks
Data Visualisation Tutorial Bootstrap
Pandas Tutorial Tailwind CSS
NumPy Tutorial SASS
NLP Tutorial LESS
Deep Learning Tutorial Web Design
Django Tutorial

Python Computer Science


Python Programming Examples Operating Systems
Python Projects Computer Network
Python Tkinter Database Management System
Web Scraping Software Engineering
OpenCV Python Tutorial Digital Logic Design
Python Interview Question Engineering Maths

DevOps Competitive Programming


Git Top DS or Algo for CP
We use cookies to ensure you AWS Top 50 Tree
have the best browsing experience on our website. By using our
site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Docker Top 50 Graph
https://www.geeksforgeeks.org/stack-in-python/ 11/13
15/03/2024 05:47 Stack in Python - GeeksforGeeks

Kubernetes Top 50 Array


Azure Top 50 String
GCP Top 50 DP
DevOps Roadmap Top 15 Websites for CP

System Design JavaScript


High Level Design JavaScript Examples
Low Level Design TypeScript
UML Diagrams ReactJS
Interview Guide NextJS
Design Patterns AngularJS
OOAD NodeJS
System Design Bootcamp Lodash
Interview Questions Web Browser

Preparation Corner School Subjects


Company-Wise Recruitment Process Mathematics
Resume Templates Physics
Aptitude Preparation Chemistry
Puzzles Biology
Company-Wise Preparation Social Science
English Grammar
World GK

Management & Finance Free Online Tools


Management Typing Test
HR Management Image Editor
Finance Code Formatters
Income Tax Code Converters
Organisational Behaviour Currency Converter
Marketing Random Number Generator
Random Password Generator

More Tutorials GeeksforGeeks Videos


Software Development DSA
Software Testing Python
Product Management Java
SAP the best browsing experience on our website. By using our C++
We use cookies to ensure you have
site, you acknowledge that you
SEO - Search haveOptimization
Engine read and understood our Cookie Policy & Privacy Policy
Data Science
https://www.geeksforgeeks.org/stack-in-python/ 12/13
15/03/2024 05:47 Stack in Python - GeeksforGeeks

Linux CS Subjects
Excel

@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved

We use cookies to ensure you have the best browsing experience on our website. By using our
site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy

https://www.geeksforgeeks.org/stack-in-python/ 13/13

You might also like