Python list.insert() function
The list.insert()
method in Python is used to add a single element at a specific position in a list. This method allows you to specify both the index where the element should be inserted and the element itself. When an element is inserted, the elements to the right of the specified index are shifted one position to the right.
Syntax
- Parameters:
index
: The position in the list where the element should be inserted. The index is zero-based, meaning the first position is0
.element
: The item to be inserted into the list.
Return Value
- The method does not return a value (
None
is returned implicitly).
Example Usage
Inserting at the Beginning of a List:
Inserting in the Middle of a List:
Inserting at the End of a List: You can insert at the end of the list by specifying an index equal to the length of the list:
Inserting Negative Indices: Python allows negative indices, which count from the end of the list. For example,
-1
refers to the last position:Inserting an Element into an Empty List: If you insert an element into an empty list, that element becomes the first and only element:
Summary
list.insert(index, element)
is a useful method for adding elements at a specific position in a list.- It modifies the original list in place, shifting other elements as necessary.
- This method can be used for various purposes, such as organizing data, maintaining order, or inserting default values into a list.