Lists in Python — Question 25
Back to all questionsWrite 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.
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.")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]
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]