Python Insert Operation
The insert()
method in Python is used to insert an element to the list at a specified index. It takes two arguments, the index on which the element needs to be inserted and the element itself.
Syntax
The syntax for insert()
method is:
list_name.insert(index, element)
Where,
list_name
: The name of the list to which an element is to be inserted.index
: The index at which the element is to be inserted.element
: The element to be inserted.
Example
# Program to illustrate insert() method in Python
fruits = ['apple', 'banana', 'cherry']
# Insert an element at a specific position
fruits.insert(1,'orange')
print(fruits)
Output
['apple', 'orange', 'banana', 'cherry']
Explanation
The insert()
method is used to insert an element at the specified index of the list. In the above example, an element 'orange'
is inserted at position 1
i.e the second position of the fruits
list.
Use
The insert()
method is used to insert an element at a specified position in a list. It is helpful when we want to add elements to the list in-between the positions of existing elements.
Important Points
- The
insert()
method inserts an element at a specified position. - The element can be of any data type such as a string, integer, float, or even another list.
- The index position starts from
0
in Python. If a negative index is provided, the element will be inserted at a position counting from the end of the list. - When an element is inserted at a specified index, all existing elements are shifted one position to the right.
Summary
In Python, the insert()
method is used to insert an element at a specified position in a list. It takes an index and the element to be inserted as arguments. The insert()
method is helpful when we want to add elements to the list in-between the positions of existing elements.