Python List insert() Method

Python list insert() method is “used to insert an element to the list at the specified index.”


list.insert(index, element)


The insert() function takes two parameters:

  1. index – It is a required parameter and a position where an element needs to be inserted.
  2. element – It is a required parameter, which is the element to be inserted in the list.

Return value

The insert() method doesn’t return anything; returns None. It only updates the current list.

Example 1: How to Use list.insert() Method

GoT = ['Daenerys', 'Jon', 'Tyrion']
GoT.insert(1, 'Varys')



Python List Insert Example | insert() Method Tutorial

Example 2: Inserting a Tuple (as an Element) into the List

To insert a tuple in List in Python, use the list.insert() method. We can also add a Tuple as an element to the specified position.

GoT1_list = ['Daenerys', 'Jon', 'Tyrion']

Friends1_tuple = ('Rachel', 'Monica', 'Phoebe')

GoT1_list.insert(2, Friends1_tuple)



Inserting a Tuple as an Element to the List

Example 3: AttributeError: ‘str’ object has no attribute ‘insert’

If we try to insert anything in a string because the string doesn’t have attribute insert().

# AttributeError
string = "192111"
string.insert(10, 1)


AttributeError: 'str' object has no attribute 'insert'

Example 4: Insert in a List Before any Element

listA = [11, 21, 19, 46, 18]

# Element to be inserted
element = 20

# Element to be inserted before 3
beforeElement = 46

# Find index
index = listA.index(beforeElement)

# Insert element at beforeElement
listA.insert(index, element)


[11, 21, 19, 20, 46, 18]

Example 5: Adding an Element to the Beginning of a List

data = ['bmw', 'audi', 'mercedez']

data.insert(0, 'jaguar')


['jaguar', 'bmw', 'audi', 'mercedez']

That’s it!

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.