-1

I got list of integers and keywords and i'm trying to remove only zeros from list with for loop - continue, but keyword False removes too, and how to prevent removing False ? ? ?

a = [1,2,0,1,0,1,None,0,False]

for x in a:
    if x ==0:
        continue
eyllanesc
  • 235,170
  • 19
  • 170
  • 241
Xocho
  • 3
  • 1
  • You could convert it to `str(x)` for the comparison – G. Anderson Jun 12 '19 at 15:52
  • 1
    A better approach is `type(x) is int` or `x == 0 and x is not False` – qwr Jun 12 '19 at 15:53
  • ^ no, a better approach would be `not (isinstance(x, int) and x == 0)` – cs95 Jun 12 '19 at 15:55
  • `str(x)` is atrocious (false positive on the string `'0'`, for starters). `type(x) is int` works, but only if you do not expect floats (0.0 will not be matched) or subclasses of int. The `isinstance` way fails because `isinstance(False, int)` is `True` (booleans are a subclass of integers). In short: go see the duplicate, where the accepted answer is fine. – Leporello Jun 12 '19 at 15:59

1 Answers1

0

To compare to exactly 0 use the is keyword:

a = [1,2,0,1,0,1,None,0,False]

for x in a: 
    if x is 0:
        continue
    print(x)
Jab
  • 26,853
  • 21
  • 75
  • 114
  • 1
    -1 because although in works in that exact case (on the standard Python implementation), it will fail with no apparent reason when the value to compare to is a different integer or a float. See https://stackoverflow.com/questions/306313/is-operator-behaves-unexpectedly-with-integers – Leporello Jun 12 '19 at 16:02
  • Thank you it works good, Suddenly i could not think about keyword is to use, – Xocho Jun 12 '19 at 17:38