Python List insert() Method

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

Syntax

list.insert(index, element)

Parameters

  1. index(required) – It is the position where an element needs to be inserted.
  2. element(required) – It is the element to be inserted in the list.

Return value

This method doesn’t return anything; returns None. It only updates the current list.

Example 1: How to Use List insert() Method

Visual Representation of How to Use list.insert() Method

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

print(GoT)

Output

['Daenerys', 'Varys', 'Jon', 'Tyrion']

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

Visualization Inserting Tuple (as an Element) into List using list.insert() method

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

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

GoT1_list.insert(2, Friends1_tuple)

print(GoT1_list)

Output

['Daenerys', 'Jon', ('Rachel', 'Monica', 'Phoebe'), 'Tyrion']

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)
print(string)

Output

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)
print(listA)

Output

[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')
print(data)

Output

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

Leave a Comment

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