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



Share this Tutorial / Exercise on : Facebook and Twitter

Python: Tips of the Day

Inserting if statements using conditional list comprehensions:

x = [1, 2, 3, 4, 5, 6]
result = []
for idx in range(len(x)):
    if x[idx] % 2 == 0:
        result.append(x[idx] * 2)
    else:
        result.append(x[idx])
result

Output:

[1, 4, 3, 8, 5, 12]
[(element * 2 if element % 2 == 0 else element) for element in x]

Output:

[1, 4, 3, 8, 5, 12]
[element * 2 for element in x if element % 2 == 0]

Output:

[4, 8, 12]