What will be the output of the following Python code? names = ["Aman",…

2024

What will be the output of the following Python code?

names = ["Aman", "Rahul", "Peter"]

names.insert(1, "John")

print(names[1])

  1. A.

    Aman

  2. B.

    Rahul

  3. C.

    Peter

  4. D.

    John

  5. E.

    Error

Attempted by 32 students.

Show answer & explanation

Correct answer: D

Concept

Python's list.insert(i, x) places x at position i and shifts every element that was at index i or later one position to the right. It does not overwrite; the list grows by one and existing items keep their relative order. Note this is different from list[i] = x (assignment), which replaces in place without shifting.

Applying it here

  1. Start: the list holds Aman, Rahul, Peter at indices 0, 1, 2.

  2. insert(1, "John") puts "John" at index 1 and pushes Rahul and Peter one slot right.

  3. List is now Aman, John, Rahul, Peter at indices 0, 1, 2, 3.

  4. print(names[1]) reads index 1, which now holds "John".

Cross-check

The pre-insert element at index 1 (Rahul) was not removed, only relocated to index 2, so reading index 1 after the insert returns the newly inserted value, John.

Explore the full course: Ibps So It Mains

Loading lesson…