w3resource

Python List: insert() Method

insert() Method

The insert() method is used to insert an item at a given position in a list.

Visual Explanation:

Python List: insert() method

So a.insert(0, x) inserts at the front of the list, and a.insert(len(a), x) is equivalent to a.append(x).

Syntax:

list.insert(i, element)

Parameter:

  • index - The first argument is the index of the element before which to insert.
  • element - Element to be inserted in the list.

Return Value from insert() method

None. It only updates the current list.

Example 1: Insert a given value at the specified position

# colors list
colors = ['Red', 'Green', 'Black']
print("Original list:") 
print(colors)  
print("Insert 'White' at the second position in the said list:")
colors.insert(1, "White")
print(colors)

Output:

Original list:
['Red', 'Green', 'Black']
Insert 'White' at the second position in the said list:
['Red', 'White', 'Green', 'Black']

Example 2: Insert a list to the list of lists in the specified position

# colors list
nums = [[1,2,3], [1,2], [4,5,6], [4,5]]
print("Original list:") 
print(nums) 
n = [-1,0,2]
nums.insert(2, n)
print("\nInsert a list at the second position of the said list of lists:")
print(nums)

Output:

Original list:
[[1, 2, 3], [1, 2], [4, 5, 6], [4, 5]]

Insert a list at the second position of the said list of lists:
[[1, 2, 3], [1, 2], [-1, 0, 2], [4, 5, 6], [4, 5]]

Python Code Editor:

Previous: Python List index() Method.
Next: Python List pop() Method.

Test your Python skills with w3resource's quiz



Follow us on Facebook and Twitter for latest update.