Search code examples
pythongeneratorgenerator-expression

Generator comprehension which adds different numbers of the same item


Given:

foo = (a,b,c,d,e,f)
multi = (b,d)

What generator comprehension gives the following tuple:

((a, None),
(b, True),
(b, False),
(c, None),
(d, True),
(d, False),
(e, None),
(f, None))

where items in multi appear twice with True and False, while other appear as None.


Solution

  • You can use a nested loop and pick one or the other iterable based on a membership test:

    ((v, other) for v in foo for other in ((True, False) if v in multi else (None,)))
    

    The nested for loop version of the above is:

    def gen():
        for v in foo:
            iterable = (True, False) if v in multi else (None,)
            for other in iterable:
                yield (v, other)