0

I have two lists

x=[0.0, -0.9000000000000199, 2.1499999999999773, 1.799999999999983, -1.5000000000000284, -2.3500000000000227, -3.05000000000004, 2.0999999999999943, 3.9999999999999716, 1.8499999999999943, -4.650000000000006, 11.349999999999994]
y=[-5.750000000000028, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]

I use below logic to remove zero completely. But zeroes of y are not completely removed.

for i in x:
    if i==0:
        x.remove(i)

for j in y:
    if j==0:
        y.remove(j)
        
print(x)
print(y)

I get the output as follows, ie I still have zero in my y list.

[-0.9000000000000199, 2.1499999999999773, 1.799999999999983, -1.5000000000000284, -2.3500000000000227, -3.05000000000004, 2.0999999999999943, 3.9999999999999716, 1.8499999999999943, -4.650000000000006, 11.349999999999994]
[-5.750000000000028, 0.0, 0.0, 0.0, 0.0, 0.0]
Vishal Naik
  • 134
  • 12

3 Answers3

3

You should not remove elements from a list while iterating over it. Instead, use a list comprehension:

x=[e for e in x if e]
y=[e for e in y if e]
whackamadoodle3000
  • 6,684
  • 4
  • 27
  • 44
  • yes, it works. But please provide some explanation on why not remove elements from a list while iterating over it. So that I can accept your answer. – Vishal Naik Oct 09 '20 at 16:43
1

Try it with y = [i for i in y if i != 0]

Rickaldo
  • 11
  • 1
1

The method "remove" only removes the first occurrence of a provided value:

def remove(self, *args, **kwargs): # real signature unknown
    """
    Remove first occurrence of value.
    
    Raises ValueError if the value is not present.
    """
    pass

To remove all values from a list, you can use the following small method:

def remove_all_values_from_list(l, val):
    for i in range(l.count(val)):
        l.remove(val)

Output:

[-0.9000000000000199, 2.1499999999999773, 1.799999999999983, -1.5000000000000284, -2.3500000000000227, -3.05000000000004, 2.0999999999999943, 3.9999999999999716, 1.8499999999999943, -4.650000000000006, 11.349999999999994]
[-5.750000000000028]