1

What I'd like is this:

>>> [i if i!= 0 for i in [0,1,2,3]]
[1,2,3]

just like

>>> [i for i in [1,2,3,4]]
[1,2,3,4]

What's the simple solution that doesn't yield a syntax error?

Edit: assuming I don't want to use a for loop and appending all elements to a new list.

1
  • if comes later: [i for i in [0,1,2,3] if i!= 0 ]
    – ayhan
    Apr 29, 2017 at 20:54

4 Answers 4

3

use [i for i in [0,1,2,3] if i!=0] to get

[1, 2, 3]

1

You can add if at the end:

[i for i in [0,1,2,3] if i!= 0]
1

Just put the if i != 0 at the end of the list comprehension, like this:

[i for i in [0,1,2,3] if i!=0]
0
[i for i in [0,1,2,3] if 1 != 0]

Not the answer you're looking for? Browse other questions tagged or ask your own question.