-1

I'm trying to understand how remove zeros from an array.

i try this:

V = [[1,2,0,3,4,0,0,5,0,6,7,8,0,9,10]]

LV = (len(V),len(V[0]))

for i in range(0,LV[1]):

    if V[0][i] == 0:

        V.remove(V[0][i])

And I get this error:

ValueError: list.remove(x): x not in list

Any idea?

martineau
  • 112,593
  • 23
  • 157
  • 280
Cain9745
  • 35
  • 3
  • 2
    `V` has a single element, a list. `0` is not a list. – gre_gor May 10 '22 at 22:41
  • 1
    But `V[0]` *is* a list, so if using a `for` loop in a [list comprehension](https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions) is OK: `V[0] = [value for value in V[0] if value != 0]` – martineau May 10 '22 at 22:48
  • @martineau That dupe target is about modifying list entries not removing them. – gre_gor May 10 '22 at 22:52
  • My [answer](https://stackoverflow.com/a/4082739/355230) to it also describes how to delete entries — but I will change the target to something more direct. – martineau May 10 '22 at 22:56
  • Actually it would be more efficient to use `V[0][:] = [value for value in V[0] if value != 0]` (if you read @Alex Martelli's answer to the duplicate question). – martineau May 10 '22 at 23:04
  • Thank you, it works well for 1D array, how you apply the same logic for a matrix? – Cain9745 May 10 '22 at 23:49

1 Answers1

-1
for i in range(V.count(0)):
    V.remove(0)
BanjoMan
  • 120
  • 1
  • 7