N
N
Nikita2018-03-29 22:58:56
Python
Nikita, 2018-03-29 22:58:56

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)

Output:
Before removal [1, 0, 2, 0, 3, 4, 5, 0, 6, 7, 8, 9]
Array_counter = [1, 3, 7]
Index of element with null value = 1
Index of element with null value = 3
Index of element with zero value = 7
Removed all zeros [0, 2, 0, 4, 5, 0, 6, 8, 9]

Answer the question

In order to leave comments, you need to log in

3 answer(s)
S
Stanislav Pugachev, 2018-03-29
@Stqs

>>> a = [1, 2, 3, 4, 5]
>>> a.remove(3)
>>> a
[1, 2, 4, 5]
>>> del a[3]
>>> a
[1, 2, 4]

R
Ruslan., 2018-03-30
@LaRN

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.

D
Dmitry, 2018-03-30
@Trif

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 question

Ask a Question

731 491 924 answers to any question