Class 12 Computer Science Data Structure
in Python Handout
Table of Contents
1. Data structure in Python
2. What is Stack
1. Operations on Stack
2. Working with stack using list.
3. Practice Questions – Part 1
4. Practical Implementation of stack using list
Data Structure
A data structure in python can be defined as a structure which can holds
related data. In other words we can say that data structure is a way of
storing, organizing and fetching data in computer. There are four data
structure in python :
1. List
2. Tuple
3. Dictionary
4. Set
In this handout we will learn that how List can be implemented as STACK
STACK :
A stack is a linear data structure in python in which addition and deletion
of elements can be done at one end only. A stack is known as LIFO (Last –
In, First – Out) data structure in python. LIFO means the elements which
are added in the last would be the first one to remove. Examples of stack
are pile of books, pile of plates or stack of carom coins.
In above pile of rings the ring which we placed first is at the bottom and
the ring which we placed in last is at the Top, So we can say that Stack is
linear list implemented as LIFO.
Operations on Stack:
There are two main operations on Stack:
Addition of element on the Top of the Stack is called PUSH.
1. push (4)
2. push (7)
3. push ("a")
4. push ("Suman")
Above operations will form the stack as shown below :
Class 12 Computer Science Data Structure in Python
Handout
So you can observe that the element which we inserted first is coming at
the bottom of the stack.
In the form of List the above stack can be shown as.
Removal of elements from the top of the Stack is called POP.
In the form of List the above stack will be represented as shown below
Class 12 Computer Science Data
Structure in Python Handout
Working with Stack using List:
The implementation of stack using list is a simple process as there are
inbuilt function which we used during working with stack. Basic
operations that we should know are :
1. How to create an empty stack?
2. How to add elements to a stack?
3. How to delete / remove elements from the stack
4. How to traverse or displaying elements of stack?
5. How to check for empty stack?
1. Creating an Empty Stack : An empty stack can be created by using
the following code
st = [ ] or st = list( ) #Here st is an empty stack
NOTE : Working with stack is similar to working with list (we can add
element by append( ), we can remove element by pop( ) and we can
display element by using index value)
2. Adding an element to a Stack : We can add element in a stack by using
append( ) function as shown below
[Link](5)
Here element ‘5’ is added into a stack named ‘st’
NOTE : We can add element only at the end of the list as we are
implementing list as stack.
3. Deleting elements from the stack : We can delete elements from the
stack as shown below :
[Link]( )
NOTE : We can remove or delete element only from the end of the list as
we are implementing list as stack.
4. Displaying all elements of the stack : We can display all elements in
stack as shown below :
L = len(st)
for i in range(L-1, -1, -1) : #As we have to display elements in reverse order
print(st[i])
if (st == [ ]) :
print("stack is empty")
Data Structure in Python – Question Answer Session – Part 1
Q1. Expand the term LIFO.
Q2. What do you mean by Stack?
Q3. What is the difference between pop( ) and append( ) function of list?
Q4. What do you mean by data structure?
Q5. Write a code to create an empty stack named "st".
Q6. Write the technical term used for adding element in stack.
Q7. What happen when you try to delete an element from an empty stack?
Practical Implementation of Stack using
List
Q1. Write a function push(student) and pop(student) to add a new
student name and remove a student name from a list student,
considering them to act as PUSH and POP operations of stack Data
Structure in Python.
st=[ ]
def push(st):
sn=input("Enter name of student")
[Link](sn)
def pop(st):
if(st==[]):
print("Stack is empty")
else:
print("Deleted student name :",[Link]())
Q2. Write a function push(number) and pop(number) to add a number
(Accepted from the user) and remove a number from a list of numbers,
considering them act as PUSH and POP operations of Data Structure in
Python.
st=[ ]
def push(st):
sn=input("Enter any Number")
[Link](sn)
def pop(st):
if(st==[]):
print("Stack is empty")
else:
print("Deleted Number is :",[Link]())
Q3. Write a menu based program to add, delete and display the record of
hostel using list as stack data structure in python. Record of hostel
contains the fields : Hostel number, Total Students and Total Rooms
host=[ ]
ch='y'
def push(host):
hn=int(input("Enter hostel number"))
ts=int(input("Enter Total students"))
tr=int(input("Enter total rooms"))
temp=[hn,ts,tr]
[Link](temp)
def pop(host):
if(host==[]):
print("No Record")
else:
print("Deleted Record is :",[Link]())
def display(host):
l=len(host)
print("Hostel Number\tTotal Students\tTotal Rooms")
for i in range(l-1,-1,-1):
print(host[i][0],"\t\t",host[i][1],"\t\t",host[i][2])
while(ch=='y' or ch=='Y'):
print("1. Add Record\n")
print("2. Delete Record\n")
print("3. Display Record\n")
print("4. Exit")
op=int(input("Enter the Choice"))
if(op==1):
push(host)
elif(op==2):
pop(host)
elif(op==3):
display(host)
elif(op==4):
break
ch=input("Do you want to enter more(Y/N)")
Python Data Structure Practice Questions – Test 1
Q1. What do you mean by data structure?
Ans . A data structure is a way of storing, organizing and retrieving data
in a computer.
Q2. Name any one linear data structure in python.
Ans . List
Q3. Python list are ______________ in Nature (static/dynamic)
Ans. Dynamic
Q4. “Lists are dynamic in nature” What do you mean by this statement?
Ans. This means that list can be grown or shrink in size means elements
can be deleted or added in list.
Q5. What do you mean by Stack?
Ans. A stack is a linear data structure where elements can be inserted or
deleted at one end.
Q6. Name the end where we add or remove element in stack.
Ans. Top
Q7. What is the full form of LIFO?
Ans. Last In First Out
Q8. Give two example of stack from daily life.
Ans. A pile of book, a stack of carom coins etc.
Q9. Name two operations performed in stack.
Ans. Push and Pop
Q10. What is the order of inserting elements in the following stack?
Ans. Order is: A, B, C, D
Python Data Structure Practice Questions
– Test 2
Q1. Organization of data in python means ______.
Ans. Data Structure
Q2. Write the full form of the following:
a. LIFO
b. FIFO
Ans.
a. LIFO : Last In First Out
b. FIFO : First In First Out
Q3. Which data structure is represented as FIFO?
Ans. Queue
Q4. Insertion into stack is called ______ (push/pop)
Ans. Pop
Q5. Giving printing command to printer is an example of
_____ (stack/queue)
Ans. Queue
Q6. Reversing a number or a word/string is an example of ______(stack
or queue)
Ans. Stack
Q7. In stack addition or removal of elements takes place at
___ (one/both) end of the list.
Ans. One
Q8. In queue, addition of elements take place at one end and removal
of elements takes place at other end. (T/F)
Ans. True
Q9. If the elements “A”, “B”, “C” are added in the queue in
the following order,
first A then B and in last C.
In what order, it will come out of queue?
Ans. A, B, C
Q10. _________ function is used to add an element in stack.
Ans. Push/ append()
Python Data Structure Practice Questions – Test 3
Q1. Write a function Push() which takes number as argument and add in a
stack "MyValue"
Ans.
MyValue=[]
def Push(value):
[Link](value)
Q2. Write a function Push that takes "name" as argument and add in a stack
named "MyStack"
Ans
Mynames=[]
def Push(Value):
[Link](Value)
Push("Amit")
Q5. Write push(rollno) and pop() method in python:
push(rollno) --add roll number in Stack
pop() --- remove roll number from Stack.
Ans.
MyStack=[]
def Push(rollno):
[Link](rollno)
def Pop(MyStack):
if len(MyStack) > 0:
[Link]()
else:
print("Stack is empty.")
Q6. Write add(bookname) and delete() method in python to add bookname and
remove bookname considering them to act as push() and pop() operations in
stack.
Ans.
MyStack=[]
def add(bname):
[Link](bname)
def delete(MyStack):
if len(MyStack) > 0:
[Link]()
else:
print("Stack is empty. There is no book name")
Q7. Write addclient(clientname) and remove() methods in python to add new
client and delete existing client from a list "clientdetail", considering them to act
as push and pop operations of the stack.
Ans.
clientdetail=[]
def addclient(cn):
[Link](cn)
def remove():
if len(clientdetail)>0:
[Link]()
else:
print("Stack is empty")
Q8 Vedika has created a dictionary containing names and marks as key-value pairs of 5
students. Write a program, with separate user-defined functions to perform the following
operations:
1. Push the keys (name of the student) of the dictionary into a stack, where the
corresponding value (marks) is greater than 70.
2. Pop and display the content of the stack.
The dictionary should be as follows:
d={“Ramesh”:58, “Umesh”:78, “Vishal”:90, “Khushi”:60, “Ishika”:95}
Then the output will be: Umesh Vishal Ishika
def push(stk,item):
[Link](item)
def Pop(stk):
if stk==[]:
return None
else:
return [Link]()
stk=[]
d={"Ramesh":58, "Umesh":78, "Vishal":90, "Khushi":60, "Ishika":95}
for i in d:
if d[i]>70:
push(stk,i)
while True:
if stk!=[]:
print(Pop(stk),end=" ")
else:
break
Write a function in Python PUSH (Lst), where Lst is a list of numbers. From this list push all numbers
not divisible by 6 into a stack implemented by using a list. Display the stack if it has at least one
element, otherwise display appropriate error message.
def PUSH(Arr,value):
s=[]
for x in range(0,len(Arr)):
if Arr[x]%6!=0:
[Link](Arr[x])
if len(s)==0:
print("Empty Stack")
else:
print(s)
Write a function in Python PUSH(Arr), where Arr is a list of numbers. From this list push all numbers
divisible by 5 into a stack implemented by using a list. Display the stack if it has at least one element,
otherwise display appropriate error message.
def PUSH(Arr,value):
s=[]
for x in range(0,len(Arr)):
if Arr[x]%5==0:
[Link](Arr[x])
if len(s)==0:
print("Empty Stack")
else:
print(s)
Write AddCustomer(Customer) method in Python to add a new customer, considering it to act as a
PUSH operation of the stack datastructure. Also display the contents of the Stack after PUSH operation.
Details of the Customer are : CID and Name.
def AddCustomer(Customer):
cid = int(input(“Enter customer id:”))
Name = input(“Enter customer name:”))
[Link] ( [cid,Name] )
Write RemoveCustomer(Customer) method in Python to remove a Customer, considering it to
act as a POP operation of the stack datastructure. Also return the value deleted from stack.
def RemoveCustomer(Customer):
if Customer == [ ]:
print(“Underflow”)
else:
p = [Link]( )
return p