Answer the question
In order to leave comments, you need to log in
Why does the remove function from an array not work?
If there is an answer to the following question, you can stop reading further:
Why is it the value that is removed, and not the index of the remove function?
array.remove(index)
_________________________________________________________________________________
array = [1, 0, 2, 0, 3, 4, 5, 0, 6, 7, 8, 9]
print("До удаления", array)
c = 0
Array_counter = []
for i in range(len(array)):
if array[i] == 0:
Array_counter.append(i)
c = c+1
print("Array_counter = ", Array_counter)
for k in range(0, c):
m = Array_counter[k]
print("Индекс элемента с нулевым значением = ", m)
array.remove(m) # удаляем 0 с индексом m
print("Удалили все нули", array)
Answer the question
In order to leave comments, you need to log in
>>> a = [1, 2, 3, 4, 5]
>>> a.remove(3)
>>> a
[1, 2, 4, 5]
>>> del a[3]
>>> a
[1, 2, 4]
Each time after the deletion, the indices of the remaining zeros (and all other elements with indices greater than the index of the element being deleted) are changed, shifted to the beginning of the array.
Agree with LaRN ...
...and of course, use del instead of remove, because
" list. remove(x) removes the first element in the list that has the value x " ;) - so remove just works :)
In this case, the minimum code change would be:
...
for k in range(0,c)[::-1]:
m = Array_counter[k]
print("Индекс элемента с нулевым значением = ", m)
del(array[m]) # удаляем 0 с индексом m
...
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question