CBSE Class 12 Computer Science Question 58 of 68

Data Structures - I : Linear Lists — Question 14

Back to all questions
14
Question

Question 13

Find the Error. Consider the following code, which runs correctly at times but gives error at other times. Find the error and its reason.

Lst1 = [23, 34, 12, 77, 34, 26, 28, 93, 48, 69, 73, 23, 19, 88]
Lst2 = []
print("List1 originally is: ", Lst1) 
ch = int(input("Enter 1/2/3 and \
predict which operation was performed?")) 
if ch == 1:
   Lst1.append(100)
   Lst2.append(100)
elif ch == 2:
   print(Lst1.index(100)) 
   print(Lst2.index(100)) 
elif ch == 3:
   print(Lst1.pop())
   print(Lst2.pop())
Answer
Lst1 = [23, 34, 12, 77, 34, 26, 28, 93, 48, 69, 73, 23, 19, 88]
Lst2 = []
print("List1 originally is: ", Lst1) 
ch = int(input("Enter 1/2/3 and \
predict which operation was performed?")) 
if ch == 1:
   Lst1.append(100)
   Lst2.append(100)
elif ch == 2:
   print(Lst1.index(100)) # Error 1
   print(Lst2.index(100)) # Error 2
elif ch == 3:
   print(Lst1.pop())
   print(Lst2.pop()) # Error 3

When the user selects option 1 (ch == 1), the code works correctly, i.e., it appends 100 to both Lst1 and Lst2 at the end. However, errors occur when the user selects option 2 (ch == 2) or option 3 (ch == 3). The errors are as follows:

  1. Error 1 — Attempting to find the index of 100 in the list Lst1 using Lst1.index(100), an error occurs because 100 is not present in Lst1.
  2. Error 2 — Attempting to find the index of 100 in the list Lst2 using Lst2.index(100), an error occurs because 100 is not present in Lst2.
  3. Error 3 — Attempting to remove an item from an empty list Lst2 using Lst2.pop(), an error occurs because there are no items to remove.