I want to remove 0
only from my list:
>>> mylist = [0, 1, None, 2, False, 1, 0]
All of them missing False items
>>> list(filter(lambda x: x != 0, mylist))
[1, None, 2, 1] # missing False
>>> list(filter(lambda x: x != 0 and x is not type(int), mylist))
[1, None, 2, 1] # missing False
>>> list(filter(lambda x: x != 0 and x is not type(False), mylist))
[1, None, 2, 1]
>>> list(filter(lambda x: x != 0 and x is not False, mylist))
[1, None, 2, 1]
Desired output:
[1, None, 2, False, 1]
Thanks for the help.
Python bool
is a subclass of int
and False
is analogous to 0. Hence compare by equality does not yield desired output.
You can use (Note this is least preferred and you ideally should not use):
>>> list(filter(lambda x: x is not 0, mylist))
[1, None, 2, False, 1]
What you should use:
An identity check may not work out in all cases as discussed in comments. A more feasible way would be to use equality check with type check as:
>>> list(filter(lambda x: x != 0 or isinstance(x, bool), mylist))
[1, None, 2, False, 1]
Personally, not a fan of filter
and lambda
, I would use a list-comprehension which proves faster:
>>> [x for x in mylist if x != 0 or isinstance(x, bool)]
[1, None, 2, False, 1]
You can check for data type of x
also and then use !=
operator.
# works for integer 0
[x for x in mylist if type(x) != int or x != 0]
# works for float 0.0 as well
[x for x in mylist if (type(x) != int and type(x) != float) or x != 0]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With