Python program to remove a specific item using the index from an array

Published by user on

In this post, we will look at how to remove a specific item using the index from an array.

Let’s look at example input and output.

First Example:
Input: [100, 150, 200, 250, 300]

Remove the item at index 3. 
As we know, the array index starts with 0.
So, value 250 will be removed.

Output: [100, 150, 200, 300]

Second Example:
Input: [60, 70, 80, 90, 100]

Remove the item at index 2.

Output: [60, 70, 90, 100]

Program to remove element using index

Python provides a pop method that accepts the index and removes the element at that position.

from array import *
int_array = array('i', [100, 150, 200, 250, 300])
print("Array Values: " + str(int_array))

print("Remove the value at index 3.")
# 250 will be removed from the array
int_array.pop(3)

# display the modified array
print("Array after removing 3rd element: " + str(int_array))

Output

Array Values: array('i', [100, 150, 200, 250, 300])
Remove the value at index 3.
Array after removing 3rd element: array('i', [100, 150, 200, 300])

Algorithm

Step 1: Declare and initialize the array
Step 2: Remove the element at index 3 using the pop() method
Step 3: Display the modified array

Categories: python