bers
bers

Reputation: 5853

Is there a "list-membership binary if" in Python?

I am looking for some kind of "binary" (non-ternary) if that allows to define list membership in Python, similar to how it works in list comprehensions. Consider the following piece of code:

abc = (1, 0, 2)
my_list = [i for i in abc if i]
# observed: [1, 2]

a = 1
b = 0
c = 2
my_list = ["d" if a; "e" if b; "f" if c]
# expected: ["d", "f"]

While the first block works, the second does not (not surprisingly). I would find this syntax quite pythonic, however. Is there anything that comes close to it, such as

my_list = ["d" if a else Nothing; "e" if b else Nothing; "f" if c else Nothing]

Upvotes: 1

Views: 97

Answers (3)

Alain T.
Alain T.

Reputation: 42129

You could add individual sublists based on conditions multiplying the sublist by the boolean results:

my_list = ["d"]*(a>0) + ["e"]*(b>0) + ["f"]*(c>0)

Or you could write a general purpose function to create a list from value/condition pairs:

def varList(*items):
    return [n for n,c in zip(*[iter(items)]*2) if c]

my_list = varList("d",a,"e",b,"f",c)

Upvotes: 1

chepner
chepner

Reputation: 532418

The if in a list comprehension is not an expression itself, only part of the syntax of a generator expression that allows you to provide a single Boolean condition to filter what the generator produces.

Your second block can be written as

my_list = [value 
           for (value, condition) in zip(["d", "e", "f"],
                                         [a, b, c]) 
           if condition]

As pointed out by user2357112 supports Monica, this is captured by the compress type provided by the itertools module:

from itertools import compress


my_list = list(compress(["d", "e", "f"],
                        [a, b, c]))

Upvotes: 5

Tzane
Tzane

Reputation: 3472

Using a dictionary:

>>> d = {1: "d", 0: "e", 2: "f"} 
>>> [d[k] for k in d if k] 
['d', 'f']

Upvotes: 1

Related Questions