'False' is removed from the list when removing other elements from list

527 Views Asked by At

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 ?

3

There are 3 best solutions below

0
On BEST ANSWER

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.

2
On

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.

0
On

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]