Question 15 of 16intermediate🔧 ApplyLong Answer5 marks

Write a program to read elements of a list.

(a)

The program should ask for the position of the element to be deleted from the list. Write a function to delete the element at the desired position in the list.

Answer

Program to read elements of a list and delete by position

myList = [] n = int(input("Enter the number of elements: ")) for i in range(n): element = int(input("Enter element: ")) myList.append(element) print("The list is:", myList)

Function to delete element at desired position

def deleteByPosition(lst, pos): if pos >= 0 and pos < len(lst): deleted = lst.pop(pos) print("Deleted element:", deleted) else: print("Invalid position!") return lst

position = int(input("Enter the position of element to be deleted: ")) myList = deleteByPosition(myList, position) print("List after deletion:", myList)

(b)

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.

Answer

Program to read elements of a list and delete by value

myList = [] n = int(input("Enter the number of elements: ")) for i in range(n): element = int(input("Enter element: ")) myList.append(element) print("The list is:", myList)

Function to delete element by value

def deleteByValue(lst, val): if val in lst: lst.remove(val) print("Element", val, "deleted successfully") else: print("Element not found in the list!") return lst

value = int(input("Enter the value of element to be deleted: ")) myList = deleteByValue(myList, value) print("List after deletion:", myList)

Explanation

The question requires writing programs for two different deletion operations on lists. For part (a), the pop() method is used to delete an element at a specific position. The function checks if the position is valid before deletion. For part (b), the remove() method is used to delete an element by its value. The function checks if the value exists in the list before attempting deletion. Both programs first read the list elements from the user, then perform the respective deletion operation.