Python Array - Insert item at specific index


Insert Item at specific Index in Array in Python

In Python, you can insert an item at specific index in a given array using insert() method of the array instance.

In this tutorial, you will learn how to insert an item at specific index in the given Python array, with examples.

To insert an item x at specific index i in given array my_array in Python, call the insert() method on the array object, and pass the index and item as arguments to the insert() method as shown in the following code snippet.

my_array.insert(i, x)

If the item is not present in the array, then the index() throws ValueError.

If the specified index is greater than the length of the array, then the item is just appended at the end of the array.

If negative index value is given, then the index is considered relative to the end of the array.

When an item is inserted at specific index, the items from that index are shifted right by one position.

1. Insert item 99 at index = 4 in the Array

In the following program, we take an integer array my_array with some initial values, and then use insert() method to insert the item x=99 at index=4 in this array.

Python Program

import array as arr

my_array = arr.array('i', [10, 15, 20, 25, 60, 20, 40])
i = 4
x = 99
my_array.insert(i, x)

print(my_array)

Output

array('i', [10, 15, 20, 25, 99, 60, 20, 40])

Explanation

Array :   10, 15, 20, 25, 60, 20, 40
Index :    0   1   2   3   4   5   6
                           ↑
        insert item=99 at index=4
Result :  10, 15, 20, 25, 99, 60, 20, 40

2. Insert item at index>array length

Now, we shall try to insert an item in the array at index=12. But, the given array is of length 7 only. Since, the specified index is greater than the length of the array, the item is just appended to the end of the array.

Python Program

import array as arr

my_array = arr.array('i', [10, 15, 20, 25, 60, 20, 40])
i = 12
x = 99
my_array.insert(i, x)

print(my_array)

Output

array('i', [10, 15, 20, 25, 60, 20, 40, 99])

Explanation

Array :   10, 15, 20, 25, 60, 20, 40
Index :    0   1   2   3   4   5   6   7 ..  12
                                             ↑
                        insert item=99 at index=12
Result :  10, 15, 20, 25, 60, 20, 40, 99

Summary

In this Python Array tutorial, we learned how to insert an item at specific index in the Python Array, using insert() method, with examples.