4

I wrote a function to remove all zeroes from a list of elements with different datatypes. But while removing the zeroes. The boolean value 'False' is also removed. But when I change it to 'True' it is not removed. I tried many different methods for doing this, but the result is the same.

def move_zeros(array):
  for i in range(array.count(0)):
      array.remove(0)
  print(array)

move_zeros([0,1,None,2,False,1,0])

The output is

[1, None, 2, 1]

How can I do this without getting the 'False' value removed ?

JACK
  • 45
  • 4

3 Answers3

4

False and True are equal to 0 and 1 respectively. If you want to remove 0 from a list without removing False, you could do this:

my_list = [0,1,None,2,False,1,0]

my_list_without_zero = [x for x in my_list if x!=0 or x is False]

Since False is a single object, you can use is to check if a value is that specific object.

khelwood
  • 55,782
  • 14
  • 81
  • 108
0

You could try this code:

def move_zeros(array):
    for i in array:
        if (type(i) is int or type(i) is float) and i == 0:
            addr = array.index(i)
            del(array[addr])
    return array

This loops over all the items on the array, then checks if it is an integer or float and if it equals 0, then deletes it if it does. The reason False was getting removed is because False, when stored on the program, evaluates to 0.

AwesomeCronk
  • 421
  • 6
  • 16
  • a bit better to use `isinstance()` and `enumerate()` and iterate from last to first and return something – Olvin Roght Dec 05 '20 at 15:12
  • @Olvin Roght good call, I added the return in, but I don’t know enough about enumerate and isinstance to use them correctly. I guess I’ll have to research them! – AwesomeCronk Dec 05 '20 at 15:17
-1

You can try this:

def move_zeros(array):
    array = [x for x in array if x is False or x!=0]
    print(array)

move_zeros([0,1,None,2,False,1,0])

Or you can try this:

def move_zeros(array):
    newarray = []

    for x in array:
        if x is False or x!=0:
            newarray.append(x)

    print(newarray)

move_zeros([0,1,None,2,False,1,0])

after running any of this you should get [1, None, 2, False, 1]

Dharman
  • 30,962
  • 25
  • 85
  • 135
Aditya
  • 1,132
  • 1
  • 9
  • 28