87.8k views
0 votes
For adding a new element to a collection at a specified index, What method can be used?

1) add()
2) insert()
3) append()
4) push()

1 Answer

5 votes

Final answer:

To insert a new element at a specific index, we use the insert() method. The add() method is typically for adding without specifying an index, append() is to add at the end, and push() is used with stacks.

Step-by-step explanation:

When adding a new element to a collection at a specified index we generally use the insert() method. The add() method is typically not used to insert elements at a specific index. The append() method is used to add an element to the end of the collection, and push() is often associated with adding elements to the end of a stack or similar data structure.

In Python, for instance, to add a value 'x' at index 'i', you would use:

list.insert(i, x)

In Java, you might use:

list.add(i, x)
User Mtrakal
by
8.8k points