Search code examples
pythonpython-itertools

Itertools Combinations/Permutations size


Is there anyway to see the len() of an itertools.Combination or other object, really, without materializing it to a list?
I can get the cardinality of combs or permutations with the factorials,... but I want something that generalizes.

Thanks


Solution

  • For any iterable it, you can do:

    length = sum(1 for ignore in it)
    

    That doesn't create a list, so the memory footprint is small. But for many kinds of iterables, it also consumes it (for example, if it is a generator, it's consumed and can't be restarted; if it is a list, it's not consumed). There is no generally "non-destructive" way to determine the length of an arbitrary iterable.

    Also note that the code above will run "forever" if it delivers an unbounded sequence of objects.