In: Computer Science
On Python perform the following operations on numbersList = [-11, -4, 5, 12, 13, 14, 19]
a) Ask the user for an index number. Check to see if the index is in the range. If it is, pop the element from that index. Print the popped element as well as the list. If the index is out of range notify the user.
b) Improve your code by using a loop. Keep asking the user for an index until they enter an index which is in the range.
c) Improve your code further by adding an outer loop. Ask the user if they want to continue removing elements from the list. When the user is done removing elements from the list, convert the final list to a tuple and print it out.
PART 1: CODE FOR THE FOLLOWING PROGRAM:-
#list of numbers
numbersList = [-11, -4, 5, 12, 13, 14, 19]
#ask user to enter an index
index=int(input("Enter an index: "))
if index in range(-len(numbersList), len(numbersList)): #Checking if index is in range
#pop element in entered index
poppedElement=numbersList.pop(index)
#print popped element and updated list
print("The element popped is: {}".format(poppedElement))
print("The list is: {}".format(numbersList))
else:
#notify user if index is not in range
print("The index you entered is invalid")
SCREENSHOT OF THE CODE AND SAMPLE OUTPUT:-
PART 2: CODE FOR THE FOLLOWING PROGRAM:-
#list of numbers
numbersList = [-11, -4, 5, 12, 13, 14, 19]
#ask user to enter an index
index=int(input("Enter an index: "))
#Keep asking the user for an index until they enter an index which is in the range.
while index in range(-len(numbersList), len(numbersList)):
#pop element in entered index
poppedElement=numbersList.pop(index)
#print popped element and updated list
print("The element popped is: {}".format(poppedElement))
print("The list is: {}".format(numbersList))
index=int(input("Enter an index: "))
if index not in range(-len(numbersList), len(numbersList)): #Checking if index is in range
print("The index you entered is invalid")
break
SCREENSHOT OF THE CODE AND SAMPLE OUTPUT:-
PART 3: CODE FOR THE FOLLOWING PROGRAM:-
#list of numbers
numbersList = [-11, -4, 5, 12, 13, 14, 19]
#Keep asking the user for an index until they enter an index which is in the range.
ans="yes"
while(ans=="yes"):
#ask user to enter an index
index=int(input("Enter an index: "))
while index in range(-len(numbersList), len(numbersList)):
#pop element in entered index
poppedElement=numbersList.pop(index)
#print popped element and updated list
print("The element popped is: {}".format(poppedElement))
print("The list is: {}".format(numbersList))
ans=input("Do you want to continue removing element(yes/no)")
if ans=="no":
break
elif(ans=="yes"):
break
if index not in range(-len(numbersList), len(numbersList)): #Checking if index is in range
print("The index you entered is invalid")
break
#converting the final list to a tuple and print it out.
print("Remaining list in tuple form: {}".format(tuple(numbersList)))
SCREENSHOT OF THE CODE AND SAMPLE OUTPUT:-
HAPPY LEARNING