Advertisements
Advertisements
प्रश्न
Write a program to read elements of a list.
The program should ask for the value of the element to be deleted from the list. Write a function to delete the element of this value from the list.
संक्षेप में उत्तर
Advertisements
उत्तर
Program:
def deleteElementsAtIndex():
global list1
#Asking the user if he want to delete any element from the list
inp = input("Do you want to delete any element from the list? (Y/N) ")
#if user input is yes
if(inp == 'Y' or inp == 'y'):
index = int(input("Enter the index of the element you would like to delete: "))
#Using pop() function to remove the element at desired index
if(index < len(list1)):
list1.pop(index)
print("The element is deleted from the list. ")
else:
print("The index is out of range.")
deleteElementsAtIndex()
else:
print("The elements in the list",list1)
#Defining empty list
list1 = list()
#Taking the number of elements to be added as input
inp = int(input("How many elements do you want to add in the list? "))
#Taking the input from user
for i in range(inp):
a = int(input("Enter the elements: "))
list1.append(a)
#Printing the list
print("The list entered is:",list1)
#The function deleteElementsAtIndex is called to delete the element after taking user input
deleteElementsAtIndex()
OUTPUT:
How many elements do you want to add in the list? 7
Enter the elements: 1
Enter the elements: 2
Enter the elements: 3
Enter the elements: 7
Enter the elements: 6
Enter the elements: 5
Enter the elements: 4
The list entered is: [1, 2, 3, 7, 6, 5, 4]
Do you want to delete any element from the list? (Y/N) y
Enter the index of the element you would like to delete: 3
The element is deleted from the list.
Do you want to delete any element from the list? (Y/N) n
The elements in the list [1, 2, 3, 6, 5, 4]shaalaa.com
Lists Manipulation in Python
क्या इस प्रश्न या उत्तर में कोई त्रुटि है?
