Newbiew9232
Newbiew9232

Reputation: 21

Skip False while removing 0 in a list

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

Answers (2)

Djaouad
Djaouad

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 a ValueError 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

Dev Khadka
Dev Khadka

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

Related Questions