Informatics Practices
Write a program to read elements of a list and do the following:
(a) The program should ask for the position of the element to be deleted from the list and 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 and delete this value from the list.
Python List Manipulation
7 Likes
Answer
nums = eval(input("Enter list: "))
# Option (a): Delete element by position
position = int(input("Enter the position of the element to delete: "))
if 0 <= position < len(nums):
del nums[position]
print("List after deletion by position:", nums)
else:
print("Error: Position out of bounds. Please enter a valid position.")
# Option (b): Delete element by value
value = int(input("Enter the value of the element to delete: "))
if value in nums:
nums.remove(value)
print("List after deletion by value:", nums)
else:
print("Element", value, "not found in the list.")Output
Enter list: [44, 55, 66, 77, 33, 22]
Enter the position of the element to delete: 3
List after deletion by position: [44, 55, 66, 33, 22]
Enter the value of the element to delete: 22
List after deletion by value: [44, 55, 66, 33]
Answered By
3 Likes
Related Questions
Write a program to read a list of elements. Modify this list so that it does not contain any duplicate elements, i.e., all elements occurring multiple times in the list should appear only once.
Write a program to create a list of elements. Input an element from the user that has to be inserted in the list. Also, input the position at which it is to be inserted.
Write a program that accepts elements of a list S and adds all the odd values and displays the sum.
Write a program to calculate the mean of a given list of numbers.