Ternary operator in enumeration loop

580 views Asked by At

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?

1

There are 1 answers

0
Taufiq Rahman On

You misplaced the if part:

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