Which of the following command correctly insert value 5 at the third position in the list1?

To insert 5 to the third position in list1, we use which command?

To insert 5 to the third position in list1, we use which command?
A. list1.insert(3, 5)लिस्ट 1.इन्सर्ट (3, 5)
B. list1.insert(2, 5)लिस्ट1.इन्सर्ट(2, 5)
C. list1.add(3, 5)लिस्ट1. ऐड(3, 5)
D. list1.append(3, 5)लिस्ट1.append(3, 5)



Correct Answer is :A. list1.insert(3, 5)



ExplanationExecute in the shell to verify.

Inserting an element in list at specific index using list.insert()

In python list provides a member function insert() i.e.

list.insert(position, element)
It accepts a position and an element and inserts the element at given position in the list.

Let’s see an example,

Suppose we have a list of strings i.e.

# List of string list1 = ['Hi' , 'hello', 'at', 'this', 'there', 'from']
Now let insert ‘why’ at 3rd position in the list i.e.
# Add an element at 3rd position in the list list1.insert(3, 'why')
Index will start from 0 in list. So, element will be inserted at 3rd position i.e. after 0,1 & 2.
Advertisements

So, list contents will be now,

['Hi', 'hello', 'at', 'why', 'this', 'there', 'from']

Video liên quan

Postingan terbaru

LIHAT SEMUA