Python Array - Remove Item at specific Index
Remove Item at specific Index in Array in Python
In Python, you can remove an item at specific index in a given array using pop() method of the array instance.
In this tutorial, you will learn how to remove an item at specific index in the given Python array, with examples.
To remove an item at specific index i in given array my_array in Python, call the pop() method on the array object, and pass the index as argument to the pop() method as shown in the following code snippet.
my_array.pop(i)
The pop() method returns the removed item.
If the specified index is greater than or equal to the length of the array, then the pop() method raises IndexError.
If negative index value is given, then the index is considered relative to the end of the array.
1. Remove item at index = 4 in the Array
In the following program, we take an integer array my_array with some initial values, and then use pop() method to remove the item 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 = my_array.pop(i)
print("Item removed :", x)
print("Result array :", my_array)
Output
Item removed : 60
Result array : array('i', [10, 15, 20, 25, 20, 40])
Explanation
Array : 10, 15, 20, 25, 60, 20, 40
Index : 0 1 2 3 4 5 6
↑
remove item at index=4
Result : 10, 15, 20, 25, 20, 40
2. Remove item at index>array length
If we try to pass an index value greater than or equal to the length of the array, then the pop() method raises IndexError.
In the following program, we take an array of length 7
. We shall try to remove item at index=12
using pop() method.
Python Program
import array as arr
my_array = arr.array('i', [10, 15, 20, 25, 60, 20, 40])
i = 12
x = my_array.pop(i)
print("Item removed :", x)
print("Result array :", my_array)
Output
Traceback (most recent call last):
File "/Users/pythonexamplesorg/workspace/main.py", line 5, in <module>
x = my_array.pop(i)
^^^^^^^^^^^^^^^
IndexError: pop index out of range
3. Remove item at index = -3 in the Array
In the following program, we take an integer array my_array with some initial values, and then use pop() method to remove the item at index=-3
in this array. Here we have passed a negative value for index. Since the index is negative, the index is considered relative 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 = -3
x = my_array.pop(i)
print("Item removed :", x)
print("Result array :", my_array)
Output
Item removed : 60
Result array : array('i', [10, 15, 20, 25, 20, 40])
Explanation
Array : 10, 15, 20, 25, 60, 20, 40
Index : -7 -6 -5 -4 -3 -2 -1
↑
remove item at index=-3
Result : 10, 15, 20, 25, 20, 40
Summary
In this Python Array tutorial, we learned how to remove an item at specific index in the Python Array, using pop() method, with examples.