How Can We Help?
Introduction:
In this tutorial, we are going to explain how to use Python list insert() Method with basic syntax and many examples for better understanding.
Python list insert() method It inserts passed object into a given list at given index and returns updated list.
Syntax:
<list_variable_name>.insert(index, object)
Input Parameters:
- index : is the index of a list where the object need to be inserted.
- object : is the element which to be inserted into the given list.
- list_variable_name : The lists that we want to insert a new object to.
Examples
Python list insert at index example
alphabet=['a','b','c','d'] alphabet.insert(2,'g') print("Updated list: ",alphabet)
Output of example
Updated list: [‘a’, ‘b’, ‘g’, ‘c’, ‘d’]
In the above example, by applying insert() function as ” alphabet.insert(2,’g’)” , we can easily add ‘g’ at index 2 of list variable ‘alphabet’ and increase 1 element of list. Here, output returns updated list with inserted value.
Python list insert at end example
numbersList=[1,2,3,4] numbersList.insert(len(numbersList),10) print("Updated list: ",numbersList)
Output of example
Updated list: [1, 2, 3, 4, 10]
In the above example, By applying insert() function with len() as ” numbersList.insert(len(numbersList),10)”, we can easily insert a new object at the end of the our list.
Python list insert at front example
mixedList=[1,2,'o','s'] mixedList.insert(0,5) print("Updated list: ",mixedList)
Output of example
Updated list: [5, 1, 2, 3, 4]
In the above example, by applying insert() function as ” mixedList.insert(0,’g’)” , we can easily add ‘g’ at index 0 of list variable ‘mixedList’ and increase 1 element of list at front. Here, output returns updated list with inserted value.
In this tutorial, you have learned how to the lower index value of passed object in the list using Python list index() method.
Hopefully, it was clear and concise.
If you have an inquiry or doubt don’t hesitate to leave them in the comment section. we are waiting for your feedback.
Similar Python list Methods:
- list.append(object) : It appends object to the given list.
- list.count(object) : It returns count of how many times object occurs in the list.
- list.extend(seq) : It appends object to the given list.
- list.index(object) : It returns the lower index value of passed object in the list, if object is present in the list.
- list.pop(obj=list[-1]) : It removes last object from the list and returns removed object of a list.
- list.remove(object) : It removes object from the list.
- list.reverse() : It reverses objects of list in place.
- list.sort([func]) : It sorts objects of a list and use compare func, if given.
Python tutorials list:
- Python tutorials list : access all python tutorials.