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. 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.
Question
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.
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.
✨ Free AI Tools for You
Powered by Chatterbot AI
Answer
Here is a Python program to read elements into a list and then provide functionality for deleting an element by its position or by its value.
# Function to delete an element at a desired position
def delete_by_position(lst, pos):
if 0 <= pos < len(lst):
lst.pop(pos)
else:
print("Position out of range")
# Function to delete the first occurrence of an element by its value
def delete_by_value(lst, value):
if value in lst:
lst.remove(value)
else:
print("Value not found in the list")
# Main program
if __name__ == "__main__":
# Read elements into the list
myList = []
n = int(input("How many elements do you want to enter in the list: "))
for i in range(n):
elem = input(f"Enter element {i+1}: ")
myList.append(elem)
print("\nCurrent List:", myList)
# Delete by position
pos = int(input("\nEnter the position of the element to be deleted: "))
delete_by_position(myList, pos)
print("List after deleting element by position:", myList)
# Delete by value
value = input("\nEnter the value of the element to be deleted: ")
delete_by_value(myList, value)
print("List after deleting element by value:", myList)
This program includes two functions:
delete_by_position(lst, pos)
: This function removes the element at the given position.delete_by_value(lst, value)
: This function removes the first occurrence of the element with the given value.
The program then reads a list of elements, allows the user to delete an element by position, and delete an element by value.
India's 1st AI Doubt Solver for CBSE, JEE, and NEET
Ask a Question for Freeand then it's just ₹212 a month