Home » Python

Python List | insert() Method with Example

Python List insert() Method with Example: In this article, we are going to learn about list.insert() Method with Example.
Submitted by IncludeHelp, on August 14, 2018

list.insert() Method

insert() is an inbuilt method in python, which is used to add an element /item at specified index to the list.

insert() is able to add the element where we want i.e. position in the list, which we was not able to do the same in list.append() Method.


    list.insert(index, element)


  • list is the name of the list.
  • index is the valid value of the position/index.
  • element is an item/element to be inserted.

Return type: Method insert() does not return any value, it just modifies the existing list.


# Python program to demonstrate
# an example of list.insert() method 

# list
cities = ['New Delhi', 'Mumbai']

# print the list
print "cities are: ",cities

# insert 'Bangalore' at 0th index
index = 0 

# insert 'Chennai' at 2nd index
index = 2 
cities.insert(index, 'Chennai')

# print the updated list
print "cities are: ",cities


    cities are:  ['New Delhi', 'Mumbai']
    cities are:  ['Bangalore', 'New Delhi', 'Chennai', 'Mumbai']


  • Initially there were two elements in the list ['New Delhi', 'Mumbai'].
  • Then, we added two more city names (two more elements) - 1) 'Bangalore' at 0th index and 2) 'Chennai' at 2nd index after adding 'Bangalore' at 0th index, by using following python statements:
  • # insert 'Bangalore' at 0th index
    index = 0
    cities.insert(index, 'Bangalore')
    # insert 'Chennai' at 2nd index
    index = 2 
    cities.insert(index, 'Chennai')
  • After inserting 'Bangalore' at 0th index, the list will be ['Bangalore', 'New Delhi', 'Chennai'].
  • And, then we added 'Chennai' at 2nd index. After inserting 'Chennai' at 2nd index. The list will be ['Bangalore', New Delhi', 'Chennai', 'Mumbai'].

So, it is at our hand, what we have to do? If our requirement is to add an element at the end of the list - use list.append() Method, or if our requirement is to add an element at any index (any specified position) - use list.insert() Method.



Comments and Discussions



Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© some rights reserved.