Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 ?

like image 764
JACK Avatar asked Oct 14 '25 18:10

JACK


1 Answers

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.

like image 75
khelwood Avatar answered Oct 17 '25 13:10

khelwood



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!