Numpy arrays have a fixed size, hence you cannot simply delete an element from them. The simplest way to achieve what you want is to use slicing:

a = a[3:]

This will create a new array starting with the 4th element of the original array.

For certain scenarios, slicing is just not enough. If you want to create a subarray consisting of specific elements from the original array, you can use another array to select the indices:

>>> a = arange(10, 20)
>>> a[[1, 4, 5]]
array([11, 14, 15])

So basically, a[[1,4,5]] will return an array that consists of the elements 1,4 and 5 of the original array.

Answer from Björn Pollex on Stack Overflow
Discussions

Problem deleting array elements: "cannot delete array elements".
I have a problem that I can't find a solution to no matter how many times I think about it. I have a program in which I generate a programming python More on holadevs.com
🌐 holadevs.com
1
2
November 22, 2017
Basic Python help? I need to let user to delete elements from an array
The issue you're encountering arises because you're modifying the stack list while iterating over it, and the indices of the items in the list are shifting as a result of deletions. However, in your provided code, the loop for iterating and printing the stack is separate from the loop where deletions are handled, so it shouldn't cause a problem in this specific case. In the provided code snippet, the core logic is contained within a while True loop that continuously prompts the user for an index to delete until an empty string is entered. When an index is provided, it is checked against the bounds of the list, and if valid, the item at that index is removed using del stack[index]. Here's a slightly cleaned-up version of your code with better structure and explanation to ensure it functions as intended: # Initial stack of elements stack = [3, 4, 5, 22] # Start of the infinite loop to process user inputs while True: # Ask the user for an index to remove input1 = input("Give me a number (or press Enter to exit): ") # Break the loop if the input is an empty string if input1 == "": break try: # Convert the input to an integer and adjust for zero-based index index = int(input1) - 1 # Check if the index is within the valid range if 0 <= index < len(stack): # Delete the element at the provided index del stack[index] else: # Notify the user if the index is out of bounds print("Invalid index. Please enter a valid index.") except ValueError: # Handle cases where the input is not an integer print("Invalid input. Please enter a valid integer.") # Display the remaining elements in the stack print("Remaining elements in stack:") for element in stack: print(element) Explanation: Loop: The code runs in a continuous loop until the user enters an empty string to exit. Input Handling: It collects an index from the user, checks if it's within the list's bounds, and if so, deletes the corresponding element. Error Handling: The code handles invalid inputs gracefully, either non-integer values or out-of-range indices. State Update: After each operation, it prints the current state of the stack. This structure ensures that the indices you're working with are always up-to-date after each deletion, preventing any off-by-one or out-of-bound errors. More on reddit.com
🌐 r/CodingHelp
1
2
May 3, 2024
Cannot delete element from django arrayfield - Stack Overflow
n_id is the note's id and c_id is contact's id. When i try to do this i am getting the error ValueError: list.remove(x): x not in list . I've checked and the c_id is in the arrayfield. More on stackoverflow.com
🌐 stackoverflow.com
delete - Can't remove element from the array - Unix & Linux Stack Exchange
Does anyone can explain me why the pid is not deleted from my pids list ? The for loop still occure the same number of time each time I go in this The var i is equal of the number of pids. So the l... More on unix.stackexchange.com
🌐 unix.stackexchange.com
🌐
YouTube
youtube.com › hey delphi
Array : Python "Value Error: cannot delete array elements" -- Why am I getting this? - YouTube
Array : Python "Value Error: cannot delete array elements" -- Why am I getting this?To Access My Live Chat Page, On Google, Search for "hows tech developer c...
Published   May 14, 2023
Views   34
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Errors › Non_configurable_array_element
TypeError: can't delete non-configurable array element - JavaScript | MDN
July 8, 2025 - The JavaScript exception "can't delete non-configurable array element" occurs when it was attempted to shorten the length of an array, but one of the array's elements is non-configurable.
Top answer
1 of 1
2
NumPy arrays are not resizable and do not allow dynamic typing. This is because efficiency is sought, using compiled C code below in the most straightforward way possible. This implies that resizing an array means creating a new array. This is why del does not work. There are two ways to remove elements from a NumPy array, both involve creating a copy of the array and it is this copy that is returned (because as mentioned above it is not possible to do inplace): - Using the method numpy.delete >>> import numpy as np # Eliminar el primer elemento: >>> a = np.array([1, 2, 3, 4]) >>> a = np.delete(a, 0) >>> a array([2, 3, 4]) # Eliminar el último elemento >>> a = np.array([1, 2, 3, 4]) >>> a = np.delete(a, a.shape[0] - 1) >>> a array([1, 2, 3]) # Eliminar el primero y el último: >>> a = np.array([1, 2, 3, 4]) >>> a = np.delete(a, (0, a.shape[0] - 1)) >>> a array([2, 3]) It receives three parameters: The array as the first argument. The index (or iterable with the indexes) of the element(s) to be deleted as the second argument. The axis on which the third party acts. Note: In the future (according to the developers themselves) np.delete will allow the use of negative indices, so we will be able to change a = np.delete(a, a.shape[0] - 1) by a = np.delete(a,- 1) . - Use slicing techniques on the array. This option is usually more efficient, especially if we only remove from the beginning or the end of the array: >>> import numpy as np #Eliminar el primer elemento >>> a = np.array([1, 2, 3, 4]) >>> a = a[1:] >>> a array([2, 3, 4]) # Eliminar el último elemento >>> a = np.array([1, 2, 3, 4]) >>> a = a[:-1] >>> a array([1, 2, 3]) # Eliminar el primero y el último: >>> a = np.array([1, 2, 3, 4]) >>> a = a[1:-1] >>> a array([2, 3]) If you intended to use the element returned by list.pop In this case you must first obtain the element by indexing and then apply the elimination with one of the two methods. It would also be possible to convert the array to a list or a queue (if add and remove operations are going to predominate at the ends), bearing in mind that there may be implications for type switching and efficiency penalties when switching to using a list or similar (in addition to not being able to use NumPy's own methods with it): >>> import numpy as np >>> a = np.array([1, 2, 3, 4]) >>> a = a.tolist() >>> a [1, 2, 3, 4] >>> a.pop() >>> a [1, 2, 3] >>> del(a[0]) >>> a >>> [2, 3] If you are not interested in using NumPy arrays you should simply make your function return a list. If I0s is simply the result of concatenating two lists, as you seem to indicate in the code, just do just that: >>> I0smallst = [1] >>> I0bigst = [2, 5] >>> I0s = I0smallst + I0bigst >>> [1, 2, 5]
🌐
YouTube
youtube.com › watch
Solving ValueError: cannot delete array elements When Working with Numpy Arrays in Python Lists - YouTube
Discover how to handle the common `ValueError` when deleting elements from numpy arrays within Python lists. Follow this detailed guide to learn effective so...
Published   May 26, 2025
Views   0
🌐
Awscd
awscd.com › ErrorMessage › Python › can-not-delete-array-element.html
Python can not delete array element
NumPyで任意の行・列を削除するdeleteの使い方 | note.nkmk.me https://note.nkmk.me/python-numpy-delete/ Python NumPy: Remove specific elements in a numpy array https://www.w3resource.com/python-exercises/numpy/python-numpy-exercise-89.php
🌐
Awscd
awscd.com › ErrorMessage › Python › valueerror-cannot-delete-array-elements.html
Python valueerror cannot delete array elements
Numpy - the best way to remove the last element from 1 dimensional ... https://stackoverflow.com/questions/32932866/numpy-the-best-way-to-remove-the-last-element-from-1-di・・・ · trimming matplotlib power spectrum chart - Stack Overflow https://stackoverflow.com/questions/12311127/trimming-matplotlib-power-spectrum-chart · Python "Value Error: cannot delete array elements" -- Why am ...
Find elsewhere
🌐
Stack Abuse
stackabuse.com › remove-element-from-an-array-in-python
How to Remove Elements from an Array/List in Python
September 15, 2023 - In this tutorial, we'll showcase examples of how to remove an element from an array in Python using remove(), pop(), the del keyword, and Numpy.
🌐
NumPy
numpy.org › doc › stable › reference › generated › numpy.delete.html
numpy.delete — NumPy v2.5 Manual
Append elements at the end of an array. ... Often it is preferable to use a boolean mask. For example: >>> arr = np.arange(12) + 1 >>> mask = np.ones(len(arr), dtype=np.bool) >>> mask[[0,2,4]] = False >>> result = arr[mask,...] Is equivalent to np.delete(arr, [0,2,4], axis=0), but allows further ...
🌐
Nanyang Technological University
libguides.ntu.edu.sg › python › deleteelementsfromarrays
NP.10 Deleting elements from arrays - Python for Basic Data Analysis - LibGuides at Nanyang Technological University
To do so, we simply need to specify ... you remove just 1 element, the array will have improper dimensions. Hence, all that can be done is to remove entire columns or rows....
🌐
Reddit
reddit.com › r/codinghelp › basic python help? i need to let user to delete elements from an array
r/CodingHelp on Reddit: Basic Python help? I need to let user to delete elements from an array
May 3, 2024 -
stack = [3, 4, 5, 22]
while True:
input1 = input("Give me number: ")
if input1 == "":
break
try:
index = int(input1) - 1
if 0 <= index < len(stack):
del stack[index]
else:
print("Invalid index. Please enter a valid index.")
except ValueError:
print("Invalid input. Please enter a valid integer.")
print("Remaining elements in stack:")
for user in stack:
print(user)
stack = [3, 4, 5, 22]
while True:
input1 = input("Give me number: ")
if input1 == "":
break
try:
index = int(input1) - 1
if 0 <= index < len(stack):
del stack[index]
else:
print("Invalid index. Please enter a valid index.")
except ValueError:
print("Invalid input. Please enter a valid integer.")print("Remaining elements in stack:")
for user in stack:
print(user)

My intention is to let user to delete certain index from the array. However, it seems like after removing an element from the stack using del stack[input1], the remaining elements shift to fill the gap. However, your loop continues to iterate over the original indices, which can lead to incorrect results.

Can anyone help me here?

Top answer
1 of 1
1
The issue you're encountering arises because you're modifying the stack list while iterating over it, and the indices of the items in the list are shifting as a result of deletions. However, in your provided code, the loop for iterating and printing the stack is separate from the loop where deletions are handled, so it shouldn't cause a problem in this specific case. In the provided code snippet, the core logic is contained within a while True loop that continuously prompts the user for an index to delete until an empty string is entered. When an index is provided, it is checked against the bounds of the list, and if valid, the item at that index is removed using del stack[index]. Here's a slightly cleaned-up version of your code with better structure and explanation to ensure it functions as intended: # Initial stack of elements stack = [3, 4, 5, 22] # Start of the infinite loop to process user inputs while True: # Ask the user for an index to remove input1 = input("Give me a number (or press Enter to exit): ") # Break the loop if the input is an empty string if input1 == "": break try: # Convert the input to an integer and adjust for zero-based index index = int(input1) - 1 # Check if the index is within the valid range if 0 <= index < len(stack): # Delete the element at the provided index del stack[index] else: # Notify the user if the index is out of bounds print("Invalid index. Please enter a valid index.") except ValueError: # Handle cases where the input is not an integer print("Invalid input. Please enter a valid integer.") # Display the remaining elements in the stack print("Remaining elements in stack:") for element in stack: print(element) Explanation: Loop: The code runs in a continuous loop until the user enters an empty string to exit. Input Handling: It collects an index from the user, checks if it's within the list's bounds, and if so, deletes the corresponding element. Error Handling: The code handles invalid inputs gracefully, either non-integer values or out-of-range indices. State Update: After each operation, it prints the current state of the stack. This structure ensures that the indices you're working with are always up-to-date after each deletion, preventing any off-by-one or out-of-bound errors.
🌐
GeeksforGeeks
geeksforgeeks.org › javascript › javascript-typeerror-cant-delete-non-configurable-array-element
JavaScript TypeError - Can't delete non-configurable array element - GeeksforGeeks
May 22, 2023 - This JavaScript exception can't delete non-configurable array element that occurs if there is an attempt to short array-length, and any one of the array's elements is non-configurable.
🌐
Quora
quora.com › How-do-I-remove-an-element-from-an-array-in-Python
How to remove an element from an array in Python - Quora
Answer (1 of 8): Depends what you mean by an array. Let us suppose you want to remove the third item (value 42) in each possibility. In the case of a numpy array, you use the delete() method, using the index (2) of the desired item to remove: [code]import numpy as np s = np.array([11, 21, 42, 6...
🌐
NumPy
numpy.org › doc › 2.2 › reference › generated › numpy.delete.html
numpy.delete — NumPy v2.2 Manual
Append elements at the end of an array. ... Often it is preferable to use a boolean mask. For example: >>> arr = np.arange(12) + 1 >>> mask = np.ones(len(arr), dtype=bool) >>> mask[[0,2,4]] = False >>> result = arr[mask,...] Is equivalent to np.delete(arr, [0,2,4], axis=0), but allows further ...
🌐
Note.nkmk.me
note.nkmk.me › home › python › numpy
NumPy: Delete rows/columns from an array with np.delete() | note.nkmk.me
February 5, 2024 - An error occurs if the specified number of elements does not match the size of the dimension. print(np.delete(a, [True, False, True], 0)) # [[4 5 6 7]] print(np.delete(a, [True, False, False, True], 1)) # [[ 1 2] # [ 5 6] # [ 9 10]] # ...
🌐
Replit
replit.com › discover › how-to-remove-an-element-from-an-array-in-python
How to remove an element from an array in Python
February 20, 2026 - Build and deploy software collaboratively with the power of AI without spending a second on setup.
Top answer
1 of 1
1

The problem is that when you do ("${pids[@]/$pid}"), it substitutes the $pid item in the array with an empty string (""). So the item isn't actually removed from the array, it's just replaced with an empty string item.

I'm guessing that after some pids gets "removed" from the array, the next cycle of for pid in "${pids[@]}", the following line will produce an error, since at least some of the $pid variables will be empty:

if [ -z "$(ps -p $pid -o pid=)" ]

This ps probably throws some error to stderr, but the output (STDOUT) of the command would be empty, so it will decrement $i by 1, and eventually $i will probably drop below zero, and since it will never be 0, the loop will never stop.

since all of the items of the in the array are numbers, you fix this by removing the quotes from the following line:

pids=("${pids[@]/$pid}")

So instead it would be:

pids=(${pids[@]/$pid})

Without the quotes the empty elements are removed from the array.

Here's a short example:

$ array=( 1 2 3 )

$ echo "${array[@]/1}"
 2 3
# Notice that the first item is replaced with an empty string

$ echo ${array[@]/1}
2 3
# Without the quotes, the empty string is removed

Notice this only works because the items in the array are numbers. It will not work if the array contains strings and spaces.

In addition, this method only substitutes substrings (and not necessarily whole array items), so for instance, if pids=( "1", "123" ), and pid=1, the result of (${pids[@]/1}) would be ( "23" ) (removing the "1" from "123", and only the "23" will remain.

See the following answer for additional details and a method to remove an item from any array regardless of the content of the array.

Disclaimer:

This answer only explains why your script didn't work as expected. My suggestion will probably make your script work, but it's not written in the most optimal way. There are many changes that could make the script cleaner and more efficient, but I'm not going into it in this answer.

🌐
DevDreamz
devdreamz.com › question › 178720-python-value-error-cannot-delete-array-elements-why-am-i-getting-this
Python "Value Error: cannot delete array elements" -- Why am I getting this? - DevDreamz
If you use numpy arrays, then use them as arrays and not as lists numpy does comparison elementwise for the entire array, which can then be used to select the relevan...