Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove only zero digit from python list?

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.

like image 321
azzamsa Avatar asked Mar 05 '23 03:03

azzamsa


2 Answers

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]
like image 186
Austin Avatar answered Mar 15 '23 09:03

Austin


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]
like image 23
Yaman Jain Avatar answered Mar 15 '23 09:03

Yaman Jain