If I! = 0 in the list comprehension gives a syntax error

This question is very similar: if / else in Python list comprehension? as well as a Simple syntax error in Python if this is an explanation of else dict . But still, I don’t understand what mistake I am making here:

[i if i!=0 for i in range(2)] ^ syntax error 

I only need entries in the list that are not zero for sparseness.

+4
source share
3 answers

Move if to the end. See Writing Python Documents in List Views .

 >>> [i for i in range(2) if i!=0] # Or [i for i in range(2) if i] [1] 

If you were looking for a conditional expression, you could do something like @Martijn,

 >>> [i if i!=0 else -1 for i in range(2)] [-1, 1] 

If you need null objects, you can also filter(...) your list.

 >>> filter(None, [1, 2, 0, 0, 4, 5, 6]) [1, 2, 4, 5, 6] 
+11
source

The if predicate appears after the for i in range(2) specification in list comprehension. You can also have an arbitrary amount of if s.

+2
source

Toggle the parts if i!=0 and for i in range(2) :

 >>> [i for i in range(2) if i!=0] [1] >>> 
+1
source

Source: https://habr.com/ru/post/1497317/


All Articles