Python List insert() Method
Inserts an element at the specified position.
Syntax
Python
Copy Code
list.insert(position, item)
Parameters
Parameter | Description |
---|---|
position |
Required. The position at which to insert the item, starting at position 0. |
item |
Required. The item to insert into the list. This item can be of any type. |
Example
Python
Copy Code
groceries = ['apples', 'oranges', 'paper towels'] groceries.insert(1, 'bananas') print(groceries)
Output
['apples', 'bananas', 'oranges', 'paper towels']
Notes
If the position is greater than the length of the list, the item is appended to the end of the list.
Example
Python
Copy Code
groceries = ['apples', 'oranges', 'paper towels'] groceries.insert(10, 'bananas') print(groceries)
Output
['apples', 'oranges', 'paper towels', 'bananas']