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])
- A.
Aman
- B.
Rahul
- C.
Peter
- D.
John
- 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
Start: the list holds Aman, Rahul, Peter at indices 0, 1, 2.
insert(1, "John") puts "John" at index 1 and pushes Rahul and Peter one slot right.
List is now Aman, John, Rahul, Peter at indices 0, 1, 2, 3.
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.