Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

if i!=0 in list comprehension gives syntax error

This question is very much like: if/else in Python's list comprehension? and Simple syntax error in Python if else dict comprehension . But still i dont understand what error I make here:

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

I only want the entries in the list that are non-zero for sparsity.

like image 414
Leo Avatar asked Dec 08 '22 13:12

Leo


1 Answers

Move the if to the end. Refer to The Python Docs entry on List Comprehensions.

>>> [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 pointed out,

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

If you just want the non zero entities, you could also filter(...) your list.

>>> filter(None, [1, 2, 0, 0, 4, 5, 6])
[1, 2, 4, 5, 6]
like image 66
Sukrit Kalra Avatar answered Dec 27 '22 04:12

Sukrit Kalra