0

In my code, I'm trying to loop through an enumeration object and selectively add some values from the enumeration to a new list using a list comprehension.

This works:

a = [1, 2, 3, 4, 5]
s = [i[1] for i in enumerate(a)]

Of course, that basically just copies list a over to s.

This doesn't work (a being the same list):

s = [i[1] if i[1] != 2 for i in enumerate(a)]

I would think that this would just copy every element of list a over to s besides the 2, but instead I get a syntax error. Anybody know what's going on here?

  • 2
    A ternary operator takes 3 operands (it's in the name). Yours only has 2, so no, that won't work. – Martijn Pieters Jan 06 '17 at 18:12
  • move the `if` to the end of the comprehension. – Dimitris Fasarakis Hilliard Jan 06 '17 at 18:13
  • Python suffers a bit from keyword overload here. `if` can used to start a conditional statement (`if ... then ... elif ... else`), in a conditional expression `(a if b else c)`, and to start filter in a generator expression or list comprehension (`[ ... for ... in ... if ... ]`). Each of the three constructs is unrelated to the others, save for using the same keyword. A few more verbose choices in the design process may have made it less confusing: `if ... then ... else`, `a when b otherwise c`, and `[ ... for ... in ... whenever ... ]`. – chepner Jan 06 '17 at 18:17

1 Answers1

0

You misplaced the if part:

  s = [i[1] for i in enumerate(a) if i[1] != 2]
Taufiq Rahman
  • 5,600
  • 2
  • 36
  • 44