Python List insert() Function
The List insert()
method inserts a single element at a specified index in a list.
Syntax
my_list.insert(index, element)
insert() Parameters
Python List insert()
method parameters::
Parameter | Condition | Description |
---|---|---|
index | Required | The index at which the element should be inserted. |
element | Required | The element to be inserted into the list. |
insert() Return Value
Python List insert()
function does not return a value: it modifies the original list.
The element
is inserted to the list at the index
-th index. All the elements after elem are shifted to the right.
Examples
Example 1: Insert an Element in a List with insert()
The insert()
method adds an element in a specified position.
For example, let's add the string 'Anna'
at index 1
in the names
list:
names = ['Tom', 'David', 'Ryan']
names.insert(1, 'Anna')
print(names) # Output: ['Tom', 'Anna', 'David', 'Ryan']
output
['Tom', 'Anna', 'David', 'Ryan']
Example 2: Insert an Element with Negative Index
You can also use negative indexing with insert()
method.
For example, let's add the string 'Anna'
at index -1
in the names
list:
names = ['Tom', 'David', 'Ryan']
names.insert(-1, 'Anna')
print(names) # Output: ['Tom', 'David', 'Anna', 'Ryan']
output
['Tom', 'David', 'Anna', 'Ryan']
Example 3: Insert an Element with Index greater than list length
When you specify an index
greater than list length, you do not get any exception. Instead, the item is inserted at the end of the list.
names = ['Tom', 'David', 'Ryan']
names.insert(10, 'Anna')
print(names) # Output: ['Tom', 'David', 'Ryan', 'Anna']
output
['Tom', 'David', 'Ryan', 'Anna']
Example 4: Insert an Element at the Beginning in a List
Just specify 0
as index of the insert()
method.
names = ['Tom', 'David', 'Ryan']
names.insert(0, 'Anna')
print(names) # Output: ['Anna', 'Tom', 'David', 'Ryan']
output
['Anna', 'Tom', 'David', 'Ryan']
insert() method vs append() method
Inserting item at the end of the list with insert()
method is equivalent to append()
method.
names = ['Tom', 'David', 'Ryan']
names.insert(len(names),'Anna') # insert at the end
print(names) # Output: ['Tom', 'David', 'Ryan', 'Anna']
# is equivalent to
names = ['Tom', 'David', 'Ryan']
names.append('Anna') # insert at the end
print(names) # Output: ['Tom', 'David', 'Ryan', 'Anna']
output
['Tom', 'David', 'Ryan', 'Anna']
['Tom', 'David', 'Ryan', 'Anna']
insert() method vs extend() method
The insert()
method consider its argument as a single object.
names = ['Tom', 'David']
names.insert(2,'Anna')
print(names) # Output: ['Tom', 'David', 'Anna']
output
['Tom', 'David', 'Anna']
If you want to add every item of an iterable to a list, you have to use extend()
method.
names = ['Tom', 'David']
names.extend('Anna')
print(names) # Output: ['Tom', 'David', 'A', 'n', 'n', 'a']
output
['Tom', 'David', 'A', 'n', 'n', 'a']