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
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
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.
No need to create a list. You can count the number of items in an iterable without storing the entire set:
sum(1 for _ in myIterable)
Yes,
def count_iterable(i):
return sum(1 for e in i)
Taken from: Is there any built-in way to get the length of an iterable in python?