Skip to content
Programming Problems · Q7

Q.Write a program to read 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 user defined function to insert the element at the desired position in the list.

Punjab PsebTextbookSubjective· 3mImportance★★★★★est
92% · 24/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 list, the element and the target position; a user-defined function validates the position and calls insert(position, element), which slots the value in at that index and shifts every later element one place right.

The idea. Insertion at a position is precisely what list.insert() provides — unlike index assignment (myList[2] = 25), which would overwrite an existing element, insert() grows the list by one and preserves everything. Wrapping it in a function adds the missing piece: validating the requested position. Because lists are mutable, the function's in-place change is visible to the caller.

Program:

def insertElement(myList, element, position):
    # Insert element at the given index position of myList
    if 0 <= position <= len(myList):        # len(myList) means 'append at end'
        myList.insert(position, element)
    else:
        print("Invalid position! Valid range: 0 to", len(myList))
    return myList

myList = eval(input("Enter the list: "))
element = eval(input("Enter the element to insert: "))
position = int(input("Enter the position (index) to insert at: "))

print("Updated list:", insertElement(myList, element, position))

Key lines: the range check allows 0 (front) through len(myList) (end — behaving like append); insert() mutates the list passed in, so the caller's list is updated too; returning it makes the function convenient to print.

Expected output (sample run):

Enter the list: [10, 20, 30, 40, 50]
Enter the element to insert: 25
Enter the position (index) to insert at: 2
Updated list: [10, 20, 25, 30, 40, 50]

Before/after picture for position 2:

| Index | 0 | 1 | 2 | 3 | 4 | 5 |

|---|---|---|---|---|---|---| …

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.