Python List insert() is a built-in function that inserts the given element at a specified index.
In this tutorial, we will learn about the Python list insert() method with the help of examples.
Syntax of List insert()
The syntax of the insert()
method is:
list.insert(index, element)
insert() Parameters
The insert()
method takes two parameters.
- index – The index or position where the elements need to be inserted.
- element – The element or value (string, number, object etc.) to be inserted in the list.
Return Value from List insert()
The insert()
method modifies the list by inserting an element at the specified position, but it does not return any value.
Notes:
- If the
index
is specified as 0, the element is inserted at the beginning of the list - If the
index>=length(list)
, the element is inserted at the end of the list
Example 1: Inserting an Element to the List
# list of vowels
vowels = ['a','e','i','o']
# insert a new vowel into a list
vowels.insert(4,'u')
# print after inserting new vowel
print("List After Inserting = ",vowels)
Output
List After Inserting = ['a', 'e', 'i', 'o', 'u']
Example 2: Inserting an element at the start and end of the list
To insert an element at the start of the list, you can give index
as 0. For inserting at the end of the list, we can give the length of the list.
Even if we give index
which is out of range, the element will get inserted at the end of the list and Python will not raise any exception.
# list of vowels
vowels = ['e','i','o']
# insert a new vowel into a list
vowels.insert(0,'a')
# print after inserting at the start of the list
print("Insert at the beginning of the list = ",vowels)
# insert a new vowel at the end a list
vowels.insert(30,'u')
# print after inserting new vowel at the end
print("Insert at the end of the list = ",vowels)
Output
Insert at the beginning of the list = ['a', 'e', 'i', 'o']
Insert at the end of the list = ['a', 'e', 'i', 'o', 'u']
Example 3: Inserting a tuple (as an element) to the list
# list of vowels
vowels = ['a','e','i']
tuple_vow = ('o','u')
# insert tuple after index 3
vowels.insert(3,tuple_vow)
# print the list with tuple
print("List with tuple = ",vowels)
Output
List with tuple = ['a', 'e', 'i', ('o', 'u')]