Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Stack and Queue in Python using queue Module
Next article icon

Stack and Queues in Python

Last Updated : 09 May, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report
Prerequisites : list and Deque in Python. Unlike C++ STL and Java Collections, Python does have specific classes/interfaces for Stack and Queue. Following are different ways to implement in Python 1) Using list Stack works on the principle of "Last-in, first-out". Also, the inbuilt functions in Python make the code short and simple. To add an item to the top of the list, i.e., to push an item, we use append() function and to pop out an element we use pop() function. These functions work quiet efficiently and fast in end operations. Let's look at an example and try to understand the working of push() and pop() function: Example: Python3
# Python code to demonstrate Implementing  # stack using list stack = ["Amar", "Akbar", "Anthony"] stack.append("Ram") stack.append("Iqbal") print(stack)  # Removes the last item print(stack.pop())  print(stack)  # Removes the last item print(stack.pop())  print(stack) 
Output:
  ['Amar', 'Akbar', 'Anthony', 'Ram', 'Iqbal']  Iqbal  ['Amar', 'Akbar', 'Anthony', 'Ram']  Ram  ['Amar', 'Akbar', 'Anthony']  
Queue works on the principle of "First-in, first-out". Below is list implementation of queue. We use pop(0) to remove the first item from a list. Python3
# Python code to demonstrate Implementing  # Queue using list queue = ["Amar", "Akbar", "Anthony"] queue.append("Ram") queue.append("Iqbal") print(queue)  # Removes the first item print(queue.pop(0))  print(queue)  # Removes the first item print(queue.pop(0))  print(queue) 
Output:
  ['Amar', 'Akbar', 'Anthony', 'Ram', 'Iqbal']  Amar  ['Akbar', 'Anthony', 'Ram', 'Iqbal']  Akbar  ['Anthony', 'Ram', 'Iqbal']  
2) Using Deque In case of stack, list implementation works fine and provides both append() and pop() in O(1) time. When we use deque implementation, we get same time complexity. Python
# Python code to demonstrate Implementing  # Stack using deque from collections import deque queue = deque(["Ram", "Tarun", "Asif", "John"]) print(queue) queue.append("Akbar") print(queue) queue.append("Birbal") print(queue) print(queue.pop())                  print(queue.pop())                  print(queue) 
Output:
  deque(['Ram', 'Tarun', 'Asif', 'John'])  deque(['Ram', 'Tarun', 'Asif', 'John', 'Akbar'])  deque(['Ram', 'Tarun', 'Asif', 'John', 'Akbar', 'Birbal'])  Birbal  Akbar  deque(['Ram', 'Tarun', 'Asif', 'John'])  
But when it comes to queue, the above list implementation is not efficient. In queue when pop() is made from the beginning of the list which is slow. This occurs due to the properties of list, which is fast at the end operations but slow at the beginning operations, as all other elements have to be shifted one by one. So, we prefer the use of dequeue over list, which was specially designed to have fast appends and pops from both the front and back end. Let's look at an example and try to understand queue using collections.deque: Python
# Python code to demonstrate Implementing  # Queue using deque from collections import deque queue = deque(["Ram", "Tarun", "Asif", "John"]) print(queue) queue.append("Akbar") print(queue) queue.append("Birbal") print(queue) print(queue.popleft())                  print(queue.popleft())                  print(queue) 
Output:
  deque(['Ram', 'Tarun', 'Asif', 'John'])  deque(['Ram', 'Tarun', 'Asif', 'John', 'Akbar'])  deque(['Ram', 'Tarun', 'Asif', 'John', 'Akbar', 'Birbal'])  Ram  Tarun  deque(['Asif', 'John', 'Akbar', 'Birbal'])  

Next Article
Stack and Queue in Python using queue Module

C

Chinmoy Lenka
Improve
Article Tags :
  • Python
  • DSA
  • python-list
  • Python-DSA
Practice Tags :
  • python
  • python-list

Similar Reads

  • Queue in Python
    Like a stack, the queue is a linear data structure that stores items in a First In First Out (FIFO) manner. With a queue, the least recently added item is removed first. A good example of a queue is any queue of consumers for a resource where the consumer that came first is served first.  Operations
    6 min read
  • 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 wi
    8 min read
  • Stack and Queue in Python using queue Module
    A simple python List can act as queue and stack as well. Queue mechanism is used widely and for many purposes in daily life. A queue follows FIFO rule(First In First Out) and is used in programming for sorting and for many more things. Python provides Class queue as a module which has to be generall
    3 min read
  • Circular Queue in Python
    A Circular Queue is a kind of queue that can insert elements inside it dynamically. Suppose, in a given array there is not any space left at the rear but we have space at the front in the normal queue it is not possible to insert elements at the front but in the case of a circular queue we can do th
    3 min read
  • numpy.stack() in Python
    NumPy is a famous Python library used for working with arrays. One of the important functions of this library is stack(). Important points:stack() is used for joining multiple NumPy arrays. Unlike, concatenate(), it joins arrays along a new axis. It returns a NumPy array.to join 2 arrays, they must
    6 min read
  • Queue Implementation in Python
    Queue is a linear data structure that stores items in a First In First Out (FIFO) manner. With a queue, the least recently added item is removed first. One can imagine a queue as a line of people waiting to receive something in sequential order which starts from the beginning of the line. It is an o
    4 min read
  • Priority Queue in Python
    A priority queue is like a regular queue, but each item has a priority. Instead of being served in the order they arrive, items with higher priority are served first. For example, In airlines, baggage labeled “Business” or “First Class” usually arrives before the rest. Key properties of priority que
    3 min read
  • Python program to reverse a stack
    The stack is a linear data structure which works on the LIFO concept. LIFO stands for last in first out. In the stack, the insertion and deletion are possible at one end the end is called the top of the stack. In this article, we will see how to reverse a stack using Python. Algorithm: Define some b
    3 min read
  • Start and stop a thread in Python
    The threading library can be used to execute any Python callable in its own thread. To do this, create a Thread instance and supply the callable that you wish to execute as a target as shown in the code given below - Code #1 : # Code to execute in an independent thread import time def countdown(n):
    4 min read
  • Monotonic Stack in Python
    A Monotonic Stack is a data structure used to maintain elements in a monotonically increasing or decreasing order. It's particularly useful in problems like finding the next or previous greater or smaller elements. In this article, we'll learn how to implement and use a monotonic stack in Python wit
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@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
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences