Follow

# prachi1179

Follow # Python Data Structure- Part 2

Prachi Agrawal
·Feb 14, 2021·

In the previous article, I have discussed some basic data structure of python. In this article, you will learn about python data structure like stack, queue and dequeue, operation performed and their implementation.

• Stack: A stack (sometimes called a “push-down stack”) is an ordered collection of items where the addition of new items and the removal of existing items always takes place at the same end. This end is commonly referred to as the “top.” The end opposite the top is known as the “base.” The ordering principle of stack is called LIFO, last-in-first-out.

Eg: stack=[1,’a’,True] Operation performed on stack: Implementation of stack:

``````class Stack:
def __init__(self):
self.items = []

def isEmpty(self):
return self.items == []

def push(self, item):
self.items.append(item)

def pop(self):
return self.items.pop()

def peek(self):
return self.items[len(self.items)-1]

def size(self):
return len(self.items)
``````
• Queue: A queue is an ordered collection of items where the addition of new items happens at one end, called the “rear,” and the removal of existing items occurs at the other end, commonly called the “front.” The ordering principle of queue is called FIFO, first-in-first-out.

Eg: queue=[1,’a’, True] Operation performed on queue: Implementation of queue:

``````class Queue:
def __init__(self):
self.items = []

def isEmpty(self):
return self.items == []

def enqueue(self, item):
self.items.insert(0,item)

def dequeue(self):
return self.items.pop()

def size(self):
return len(self.items)
``````
• Deque: A deque, also known as a double-ended queue, is an ordered collection of items similar to the queue. It has two ends, a front and a rear, and the items remain positioned in the collection. New items can be added at either the front or the rear. Likewise, existing items can be removed from either end.

Eg: deque=[1,’a’,True] Operation performed on deque: Implementation of deque:

``````class Deque:
def __init__(self):
self.items = []

def isEmpty(self):
return self.items == []

self.items.append(item)

self.items.insert(0,item)

def removeFront(self):
return self.items.pop()

def removeRear(self):
return self.items.pop(0)

def size(self):
return len(self.items)
``````