0

i am trying to delete zero values from the list using the below code

for id,row in enumerate(list):
    if row[0]=="0":
       del list(id)

this works fine for input like [0,1,3,0,9,10,0,3,0,6]

but doesn't work as expected for inputs like [0,0,1,3,4,0,0,4,5,6,0,0].

output: [0,1,3,4,0,4,5,6,0]

I guess its because the element right after the deleted one gets the id of the deleted element and enumerate increments the id which leaves the element after the one which is deleted unchecked. so what can be done to check all the elements ? is there a better way ?

Sivakami Subbu
  • 344
  • 3
  • 11
  • Possible duplicate of [Remove items from a list while iterating](https://stackoverflow.com/questions/1207406/remove-items-from-a-list-while-iterating) – Mel Dec 20 '17 at 08:46
  • @Mel- the question u have pointed doesn't provide the information i looking for – Sivakami Subbu Dec 20 '17 at 08:57
  • @Mel My requirement is to delete the **all** zero values instead of copying to another list. And the snippet i have attached can delete zero values but **cannot perform deletion when two zeroes occur together** – Sivakami Subbu Dec 20 '17 at 09:03

3 Answers3

1

I made a little change to your code:

mylist = [0,0,1,3,4,0,0,4,5,6,0,0]
for id,row in reversed(list(enumerate(mylist))):
    if(row==0):
        del mylist[id]

If you loop your list in the way you did (from start to end) and delete an element while doing it, you'll end up jumping indexes because python does not recognize that an element has been deleted from the list.
If you have an array with 10 elements inside and you delete the first (idx 0), in the next iteration you will be at index 1, but the array has been modified, so your idx 1 is the idx 2 of your array before the deletion, and the real idx 1 will be skipped.

So you just need to loop your array in reverse mode, and you won't miss indexes.

If you print the value of mylist, you'll get [1, 3, 4, 4, 5, 6].

0

This problem is documented on this python page under 8.3:

https://docs.python.org/3/reference/compound_stmts.html

They suggest doing it this way by using a slice. It works for me:

a = [-2,-4,3,4]
for x in a[:]:
    if x < 0: a.remove(x)
print ('contents of a now: ')
print(*a)
NSchorr
  • 875
  • 10
  • 13
0

enumerate returns an object called enumerate object and it is iterable not actually a list. second thing row is not a list it is not subscriptable.

 for i,row in enumerate(l):
     if row==0:
        del(l[i])

you will not get result you want this way.

try this:

t=[] #a temporary list
for i in l:
    if i!=0:
        t.append(i)

t will contain sublist of l with non zero elements. put the above inside a function and return the list t .

Bibek Ghimire
  • 522
  • 1
  • 4
  • 19