0

I have a list below Prob and I when I try to remove 0 or remove 0.0 it sometimes doesn't remove from the list or there is 'another version' of 0 still in the list. How can I make sure that all 'flavors' of zero are removed from the list since it is impossible to list out all possible decimal increments for zero?

 x = [0.0,
 0.0,
 0,
 0.0009765625,
 0.0003255208333333333,
 0.0021158854166666665,
 0.005045572916666667,
 0.013020833333333334,
 0.019856770833333332,
 0.0107421875,
 0.004557291666666667,
 0.000]
    
if 0 in probability_perpoint:
    probability_perpoint.remove(0)
if 0.0 in probability_perpoint:
    probability_perpoint.remove(0.0)

`print(x)` # still prints 0's!
maximus
  • 335
  • 2
  • 16

3 Answers3

2

Simply do this way with list comprehension,

x = [0.0,0.0,0,0.0009765625,0.0003255208333333333,0.0021158854166666665,0.005045572916666667,0.013020833333333334,0.019856770833333332,0.0107421875,0.004557291666666667,0.000]
x = [i for i in x if i != 0]
print(x)

Demo: https://rextester.com/NAVN53491

Another way with remove() and while

x = [0.0,0.0,0,0.0009765625,0.0003255208333333333,0.0021158854166666665,0.005045572916666667,0.013020833333333334,0.019856770833333332,0.0107421875,0.004557291666666667,0.000]
try:
    while True:
        x.remove(0)
except ValueError:
    pass
 
print(x)

Demo: https://rextester.com/YTXM11780

A l w a y s S u n n y
  • 36,497
  • 8
  • 60
  • 103
2

list.remove only removes the first occurrence, so you should build the list from scratch as repeated removals are expensive. Moreover, if these are results of some calculation and subject to rounding errors you might want to look at math.isclose:

import math

x[:] = [e for e in x if not math.isclose(e, 0)]
user2390182
  • 72,016
  • 6
  • 67
  • 89
0

Python's filter-function is perfect for this problem. You can specify your filter criteria in form of an anonymous lambda function as first argument and the list you would like to filter through as second argument.

x = [0.0,
 0.0,
 0,
 0.0009765625,
 0.0003255208333333333,
 0.0021158854166666665,
 0.005045572916666667,
 0.013020833333333334,
 0.019856770833333332,
 0.0107421875,
 0.004557291666666667,
 0.000]
    
result = list(filter(lambda n: n!=0, x))

print(result)

beware that you have to convert the result into a list

Bialomazur
  • 1,122
  • 2
  • 7
  • 18