2

I am going to realize the following functions: k is a list, e.g.:

k = [1,2,3,4,5,6,7,6,4,7,2,3,4,4,8,9,1,0,2,4]

I want to have a list of boolean values if the elements is in a subset of this list, e.g. if element in [2,5,9], return true, else false:

p = [False, True, False, False, True, False, False, False, False, False, True, False, False, False, False, True, False, False, True, False]

I am only capable of achieving this by standard for loops:

p = []
for element in k: 
    if element in [2,5,9]:
        p.append(True)
    else:
        p.append(False) 

However, what I want is to achieve this with a simple short-hand statements, then I wrote:

p2 = [True for i in k if i in [2,5,9] else False]

But this gives an error upon 'else':

  File "<stdin>", line 1
    p2 = [True for i in k if i in [2,5,9] else False]
                                             ^
SyntaxError: invalid syntax

So how can I correct this?

SimZhou
  • 466
  • 1
  • 7
  • 14

1 Answers1

3

This is a ternary operator, so you can write it like:

[True if i in [2, 5, 9] else False for i in k]

or more verbose:

[(True if i in [2, 5, 9] else False) for i in k]

The ternary operator itself has nothing to do with the list comprehension. You just write an expression before the for part in a list comprehension. Here this expression "happens" to be a ternary operator. So there is no confusion/ambiguity here.

But since the in operator will return True or False, you can just write:

[i in [2, 5, 9] for i in k]
Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555