
# And a queue that only has enqueue and dequeue operations class Queue: def _init_( self):ĭef dequeue( self): if len(self.queue) < 1: To do so, let's create a new file called stack_queue.py and define two classes: # A simple class stack that only allows pop and push operations class Stack: def _init_( self): We can create classes that only exposes the necessary methods for each data structure. There are times when we'd like to ensure that only valid operations can be performed on our data.
Java queue vs stack code#
If your code needed a stack and you provide a List, there's nothing stopping a programmer from calling insert, remove or other list functions that will affect the order of your stack! This fundamentally ruins the point of defining a stack, as it no longer functions the way it should. If you'd like to learn more about the deque library and other types of collections Python provides, you can read our Introduction to Python's Collections Module article. Print(numbers) # deque() # You can dequeue like a queue Python has a deque (pronounced 'deck') library that provides a sequence with efficient methods to work as a stack or a queue.ĭeque is short for Double Ended Queue - a generalized queue that can get the first or last element that's stored: from collections import deque # Now let's dequeue our fruits, we should get 'banana'Īgain, here we use the append and pop operations of the list to simulate the core operations of a queue. # Let's enqueue some fruits into our list For example, they are used for caching.Consider a "queue" of fruits: fruits =

Queues are useful when the ordering of the data matters as it preserves that ordering.Stacks can be used to implement recursive solutions iteratively.

For example, parsing questions tend to use stacks because of the LIFO property.


StacksĪ stack is a data structure that stores objects in which the most recently stored objects are the first ones to be removed, (LIFO: last in, first out). It is important to be comfortable with these two data structures because depth-first-search and breadth-first-search will use them for graph traversals. Stacks and queues are foundational data structures that are useful when adding and removing in particular orders.
