![]() |
VOOZH | about |
insert() method is used to add an element at a specific position in a list. Unlike append() which adds elements only at the end, insert() allows adding elements anywhere in the list using an index.
Example: In this example, insert() adds "apple" at index 1 in the list.
['banana', 'apple', 'cherry', 'grape']
list.insert(index, element)
Parameters:
Return: It does not return any value, but modifies the original list directly.
Example 1: In this example, an element is inserted at index 0. This places the new value at the beginning of the list.
['apple', 'banana', 'mango']
Example 2: Here, a list is inserted as a single element inside another list, creating a nested list.
[1, 2, [3, 4], 5]
Example 3: In this example, the position of an existing element is found using index() and a new value is inserted before it.
[10, 20, 30, 40, 50]
Explanation: a.index(40) finds the index of 40 and insert(i, 30) adds 30 before it.