remove an element from an array at a specific index in python

To remove an element from an array at a specific index in Python, you can use the built-in pop() method. The pop() method removes the element at the given index and returns it.

Here's an example:

main.py
my_arr = [1, 2, 3, 4, 5]
index_to_remove = 2
removed_element = my_arr.pop(index_to_remove)
print(my_arr) # Output: [1, 2, 4, 5]
print(removed_element) # Output: 3
163 chars
6 lines

In this example, we have an array my_arr containing the values [1, 2, 3, 4, 5]. We want to remove the element at index 2 (which is the value 3).

We create a variable index_to_remove to store the index we want to remove. We then call the pop() method on the array, passing in the index_to_remove variable.

The pop() method removes the element at index 2 from the array and returns it. We store the removed element in a variable removed_element.

We then print the modified array my_arr and the removed element removed_element.

The output of this program will be:

main.py
[1, 2, 4, 5]
3
15 chars
3 lines

gistlibby LogSnag