Search code examples
pythoniterator

Can I subset an Iterator and keep it an Iterator?


I have a use case where I need the permutations of boolean. However I do not need them when they are reversed. So I can do something like this:

import itertools

[
    p for p in 
    itertools.product([True,False],repeat=4)
    if p!=p[::-1]
]

This issue is that this is a list, stored in memory, and with increasing repeats I will run into memory errors.

Is it possible to "subset" an iterator while keeping it as an iterator?

If possible I am looking for a general answer, that applies to any sub setting strategy on any iterator


Solution

  • You use a generator expression, syntactically identical to a listcomp, but using parentheses rather than square brackets as the delimiter:

    (
        p for p in 
        itertools.product([True,False],repeat=4)
        if p!=p[::-1]
    )
    

    If the generator expression is the sole argument to a function, you don't even need the extra parentheses (the function call parentheses serve double duty delimiting the function argument and the genexpr).