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.

Perm. Questiin
  • 429
  • 2
  • 9
  • 21

4 Answers4

3

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

[1, 2, 3]

Vidur Khanna
  • 138
  • 7
1

You can add if at the end:

[i for i in [0,1,2,3] if i!= 0]
Spencer Wieczorek
  • 21,229
  • 7
  • 44
  • 54
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]
Anonymous1847
  • 2,568
  • 10
  • 16
0
[i for i in [0,1,2,3] if 1 != 0]
Matei
  • 1,783
  • 1
  • 14
  • 17