Google News
logo
Python Program to Remove an element from an array
There are different types of arrays in Python, such as lists and NumPy arrays. Here are examples of removing an element from both types of arrays :

Removing an element from a list :

Program :
# Define a list
my_list = [1, 2, 3, 4, 5]

# Remove an element from the list
my_list.remove(3)

# Print the updated list
print(my_list)
Output :
[1, 2, 4, 5]
In this example, we first define a list `my_list` with 5 elements. Then, we remove the element with the value 3 from the list using the `remove()` method. Finally, we print the updated list.

Removing an element from a NumPy array :

Program :
import numpy as np

# Define a NumPy array
my_array = np.array([1, 2, 3, 4, 5])

# Remove an element from the array
my_array = np.delete(my_array, 2)

# Print the updated array
print(my_array)
Output :
[1 2 4 5]
In this example, we first import the NumPy library and define a NumPy array `my_array` with 5 elements. Then, we use the `delete()` function from NumPy to remove the element at index 2 (i.e., the third element) from the array.

Finally, we print the updated array. Note that the `delete()` function returns a new array with the specified element removed, so we need to assign this new array to the variable `my_array` to update it.