Reputation: 21
I am trying to remove all the zeroes in my list which contains integers, booleans and string type data. I am aware that False is evaluated as 0 in python. But is there a way to skip False while removing 0 from my list?
while 0 in li :
li.remove(0)
Upvotes: 1
Views: 113
Reputation: 22776
Apparently, since, from the docs:
list.remove(x)
Remove the first item from the list whose value is equal to
x
. It raises aValueError
if there is no such item.
And:
>>> 0 == False
True
>>> 1 == True
True
Using list.remove
with 0
will remove False
as well (and vice-versa), and with 1
will remove True
as well (and vice-versa), so, for now it's better to use a list comprehension for this:
li = [i for i in li if type(i) != int or i]
You can also use the built-in function filter
:
li = list(filter(lambda i : type(i) != int or i, li))
Upvotes: 1
Reputation: 5471
you can use check type and 0 like below
ls = [True, False, 0, 3, 4, "abc", "xyx", 0, "o"]
[item for item in ls if (type(item)!=int) or (item!=0)]
Upvotes: 0