Skip to content
Programming Problems · Q8

Q.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.
Tripura TbseTextbookSubjective· 5mImportance★★★★★est
96% · 25/26 Questions
🔒 Locked · start free trial →

You're viewing a preview — the full solution, concept, methods & PYQ mapping are locked.

Start your 14-day free trial to unlock the full solution →

Read the elements into a list, then delete (a) by position using lst.pop(pos) and (b) by value using lst.remove(value) — each inside its own function, with validity checks so a bad position or a missing value gives a clear message instead of a crash.

The idea (List Operations). A Python list is mutable, so a function that receives it gets a reference to the same object — deleting inside the function changes the caller's list too. Python already gives us the two exact tools the question asks for: pop(index) removes the element at a position, and remove(value) removes the first element with a given value. Our job is mainly to wrap them with input reading and error checks.

Program

def delete_at_position(lst, pos):
    """Delete the element at index pos (0-based)."""
    if 0 <= pos < len(lst):
        removed = lst.pop(pos)
        print("Deleted", removed, "from position", pos)
    else:
        print("Invalid position! Valid positions are 0 to", len(lst) - 1)

def delete_by_value(lst, value):
    """Delete the first occurrence of value from the list."""
    if value in lst:
        lst.remove(value)
        print("Deleted the element with value", value)
    else:
        print(value, "is not present in the list")

# ---- main program ----
n = int(input("How many elements? "))
lst = []
for i in range(n):
    lst.append(int(input("Enter element " + str(i + 1) + ": ")))
print("The list is:", lst)

pos = int(input("(a) Enter the position of the element to delete: "))
delete_at_position(lst, pos)
print("List now:", lst)

val = int(input("(b) Enter the value of the element to delete: "))
delete_by_value(lst, val)
print("List now:", lst)

Sample run (expected output)

How many elements? 5
Enter element 1: 10
Enter element 2: 20
Enter element 3: 30
Enter element 4: 40
Enter element 5: 50
The list is: [10, 20, 30, 40, 50]
(a) Enter the position of the element to delete: 2
Deleted 30 from position 2
List now: [10, 20, 40, 50]
(b) Enter the value of the element to delete: 40
Deleted the element with value 40
List now: [10, 20, 50]

Key lines explained …

Unlock everything free for 14 days

  • Full step-by-step solutions
  • Concept-first explanations
  • Methods, shortcuts & mistakes
  • PYQ mapping + timed mock tests

Full access for 14 days. No credit card required.