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
  • 421
  • 1
  • 8
  • 20

4 Answers4

3

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

[1, 2, 3]

Vidur Khanna
  • 128
  • 7
1

You can add if at the end:

[i for i in [0,1,2,3] if i!= 0]
Spencer Wieczorek
  • 20,481
  • 7
  • 40
  • 51
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,518
  • 9
  • 15
0
[i for i in [0,1,2,3] if 1 != 0]
Matei
  • 1,763
  • 1
  • 13
  • 16